# -*- coding: utf-8 -*-
"""视频处理器模块，负责处理单个视频流的帧获取、处理和分析"""

import logging
import threading
import cv2
import time
import numpy as np
from typing import Dict, List, Optional, Any, Callable
import datetime
from datetime import timedelta
import queue
import copy
import sys
import traceback
import gc
from .scene_manager import SceneManager

logger = logging.getLogger(__name__)

# 全局异常处理装饰器
def exception_handler(func):
    """为方法提供统一的异常处理机制"""
    def wrapper(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except Exception as e:
            # 记录详细的错误信息
            error_info = {
                'method': func.__name__,
                'camera_id': getattr(self, 'camera_id', 'unknown'),
                'error_type': type(e).__name__,
                'error_message': str(e),
                'timestamp': datetime.now().isoformat(),
                'traceback': traceback.format_exc()
            }
            
            # 记录错误日志
            logger.error(f"方法 {error_info['method']} 执行失败: {error_info['error_message']}")
            logger.debug(f"详细错误信息: {error_info['traceback']}")
            
            # 更新错误统计
            if hasattr(self, '_statistics'):
                self._statistics['total_errors'] += 1
                self._statistics['last_error_time'] = datetime.now()
                
            # 触发错误回调
            if hasattr(self, '_error_callback') and self._error_callback:
                try:
                    self._error_callback(error_info)
                except Exception as cb_e:
                    logger.error(f"错误回调执行失败: {str(cb_e)}")
            
            # 对于关键方法，可以尝试自动恢复
            if func.__name__ in ['_capture_loop', '_process_loop']:
                logger.info(f"尝试自动恢复方法: {func.__name__}")
                if hasattr(self, '_attempt_recovery'):
                    self._attempt_recovery(func.__name__)
            
            # 对于非循环方法，重新抛出异常让调用者处理
            if func.__name__ not in ['_capture_loop', '_process_loop']:
                raise
        
    return wrapper


class VideoProcessor:
    """视频处理器类，负责单个摄像头视频流的处理"""
    
    def __init__(self, camera_id: str, source: str, config: Dict[str, Any] = None):
        """初始化视频处理器
        
        Args:
            camera_id: 摄像头ID
            source: 视频源（RTSP URL、文件路径或设备ID）
            config: 配置参数
        """
        self.camera_id = camera_id
        self.source = source
        self.config = config or {}
        
        # 视频捕获相关
        self.cap = None
        self.frame_width = 0
        self.frame_height = 0
        self.fps = 0
        
        # 线程控制
        self.running = False
        self.capture_thread = None
        self.process_thread = None
        self.monitor_thread = None
        self.lock = threading.RLock()
        
        # 帧缓冲队列
        self.frame_queue = queue.Queue(maxsize=10)  # 最多保存10帧
        self.processed_frame_queue = queue.Queue(maxsize=5)  # 已处理帧队列
        
        # 回调函数
        self.on_frame_callback = None  # 原始帧回调
        self.on_processed_frame_callback = None  # 处理后帧回调
        self.on_detection_callback = None  # 检测结果回调
        self.on_alert_callback = None  # 告警回调
        self.on_status_callback = None  # 状态变更回调
        self.on_error_callback = None  # 错误回调
        
        # 性能统计
        self.stats = {
            'frames_processed': 0,
            'fps': 0.0,
            'last_fps_time': time.time(),
            'last_frame_time': 0,
            'processing_time': 0,
            'avg_processing_time': 0,
            'processing_times': [],
            'capture_errors': 0,
            'process_errors': 0,
            'total_errors': 0,
            'recovery_attempts': 0,
            'successful_recoveries': 0,
            'health_checks': 0,
            'issues_detected': 0,
            # 场景相关统计
            'active_scene': None,
            'scene_activation_duration': 0,
            'last_scene_change': 0
        }
        
        # 状态信息
        self.status = 'inactive'  # inactive, starting, active, stopping, error
        self.last_error = None
        self.health_status = 'unknown'  # unknown, healthy, warning, critical
        self.is_recovering = False
        self.last_recovery_attempt = None
        
        # 目标跟踪
        self.tracks = {}
        
        # 其他配置
        self.max_frame_age = self.config.get('max_frame_age', 30)  # 最大帧缓存时间（秒）
        self.resolution = self.config.get('resolution', (0, 0))  # 目标分辨率，(0,0)表示不调整
        self.frame_interval = self.config.get('frame_interval', 1)  # 处理帧间隔
        self.use_gpu = self.config.get('use_gpu', True)
        
        # 监控和自动恢复配置
        self.monitor_interval = self.config.get('monitor_interval', 10.0)  # 监控间隔(秒)
        self.diagnosis_interval = self.config.get('diagnosis_interval', 60.0)  # 诊断间隔(秒)
        self.auto_recover = self.config.get('auto_recover', True)  # 自动恢复开关
        self.max_recovery_attempts = self.config.get('max_recovery_attempts', 3)  # 最大恢复尝试次数
        self.recovery_cooldown = self.config.get('recovery_cooldown', 60)  # 恢复冷却时间(秒)
        
        # 时间记录
        self.last_health_check = datetime.now()
        self.last_diagnosis = datetime.now()
        
        # 帧编号计数器
        self.frame_count = 0
        self.consecutive_errors = 0
        
        # 检测引擎引用
        self.detection_engine = None
        
        # 行为分析器引用
        self.behavior_analyzer = None
        
        # 场景管理器
        self.scene_manager = None
    
    def initialize(self, detection_engine=None, behavior_analyzer=None, scene_manager=None) -> bool:
        """初始化视频处理器
        
        Args:
            detection_engine: 检测引擎实例
            behavior_analyzer: 行为分析器实例
            scene_manager: 场景管理器实例
            
        Returns:
            bool: 初始化是否成功
        """
        try:
            logger.info(f"初始化视频处理器: {self.camera_id}, 源: {self.source}")
            
            # 设置外部组件引用
            self.detection_engine = detection_engine
            self.behavior_analyzer = behavior_analyzer
            self.scene_manager = scene_manager
            
            # 如果提供了场景管理器，注册场景切换回调
            if self.scene_manager:
                self.scene_manager.register_scene_change_callback(self._on_scene_changed)
            
            # 初始化视频捕获
            if not self._initialize_capture():
                logger.error(f"无法初始化视频捕获: {self.source}")
                return False
            
            self.status = 'inactive'
            self.health_status = 'unknown'
            logger.info(f"视频处理器初始化成功: {self.camera_id}")
            return True
            
        except Exception as e:
            logger.error(f"初始化视频处理器失败: {str(e)}")
            self._handle_error(e, "initialize")
            return False
            
    def _on_scene_changed(self, new_scene, old_scene):
        """场景切换回调方法
        
        Args:
            new_scene: 新激活的场景对象
            old_scene: 旧的场景对象
        """
        logger.info(f"[{self.camera_id}] 场景切换: {old_scene.name if old_scene else 'None'} -> {new_scene.name}")
        
        # 更新统计信息
        with self.lock:
            self.stats['active_scene'] = new_scene.name
            self.stats['last_scene_change'] = time.time()
            
            # 如果之前有活跃场景，计算其持续时间
            if old_scene and self.stats['scene_activation_duration'] > 0:
                old_scene.duration += time.time() - self.stats['scene_activation_duration']
            
            # 重置当前场景的持续时间计时
            self.stats['scene_activation_duration'] = time.time()
        
        # 触发状态回调
        if self.on_status_callback:
            try:
                self.on_status_callback({
                    'camera_id': self.camera_id,
                    'status': self.status,
                    'health_status': self.health_status,
                    'active_scene': new_scene.name,
                    'timestamp': datetime.now().isoformat()
                })
            except Exception as e:
                logger.error(f"场景切换状态回调失败: {str(e)}")
                
    def _monitor_system(self):
        """系统监控线程方法，定期检查系统健康状态并触发恢复机制"""
        logger.info(f"[{self.camera_id}] 监控线程已启动")
        
        while self.running:
            try:
                # 执行健康检查
                self._perform_health_check()
                
                # 定期执行诊断
                now = datetime.now()
                if (now - self.last_diagnosis).total_seconds() >= self.diagnosis_interval:
                    self._perform_diagnosis()
                
                # 检查是否需要恢复
                if self._should_recover():
                    self._attempt_recovery()
                    
            except Exception as e:
                logger.error(f"[{self.camera_id}] 监控线程异常: {str(e)}")
                
            # 等待下一次检查
            time.sleep(min(self.monitor_interval, 5.0))  # 确保不会无限等待
        
        logger.info(f"[{self.camera_id}] 监控线程已停止")
        
    def _perform_health_check(self):
        """执行健康检查，评估系统状态"""
        self.stats['health_checks'] += 1
        now = datetime.now()
        self.last_health_check = now
        
        issues = []
        health_score = 100.0
        
        # 检查视频捕获状态
        if not self._is_capture_healthy():
            issues.append("视频捕获异常")
            health_score -= 40
        
        # 检查队列状态
        if self._is_queue_backed_up():
            issues.append("队列积压")
            health_score -= 25
        
        # 检查错误率
        error_rate = self._calculate_error_rate()
        if error_rate > 0.1:  # 10% 错误率
            issues.append(f"错误率过高: {error_rate:.2%}")
            health_score -= 35
        
        # 更新健康状态
        new_health_status = 'healthy'
        if health_score < 50:
            new_health_status = 'critical'
        elif health_score < 80:
            new_health_status = 'warning'
        
        # 如果状态变化，更新并记录
        if new_health_status != self.health_status:
            logger.info(f"[{self.camera_id}] 健康状态变化: {self.health_status} -> {new_health_status}")
            self.health_status = new_health_status
            
            # 如果有问题，记录并可能触发恢复
            if issues:
                self.stats['issues_detected'] += len(issues)
                logger.warning(f"[{self.camera_id}] 检测到问题: {', '.join(issues)}")
        
        # 触发状态回调
        if self.on_status_callback:
            try:
                self.on_status_callback({
                    'camera_id': self.camera_id,
                    'status': self.status,
                    'health_status': self.health_status,
                    'issues': issues,
                    'timestamp': now.isoformat()
                })
            except Exception as e:
                logger.error(f"[{self.camera_id}] 状态回调执行失败: {str(e)}")
    
    def _handle_error(self, exception: Exception, context: str):
        """统一的错误处理方法
        
        Args:
            exception: 异常对象
            context: 错误发生的上下文
        """
        error_info = {
            'context': context,
            'error_type': type(exception).__name__,
            'error_message': str(exception),
            'timestamp': datetime.now().isoformat(),
            'traceback': traceback.format_exc()
        }
        
        logger.error(f"[{self.camera_id}] 在{context}过程中发生错误: {error_info['error_message']}")
        logger.debug(f"[{self.camera_id}] 详细错误信息: {error_info['traceback']}")
        
        # 更新统计信息
        self.stats['total_errors'] += 1
        if context == 'capture':
            self.stats['capture_errors'] += 1
        elif context == 'process':
            self.stats['process_errors'] += 1
        
        # 更新状态
        self.last_error = error_info['error_message']
        self.status = 'error'
        
        # 增加连续错误计数
        self.consecutive_errors += 1
        
        # 触发错误回调
        if self.on_error_callback:
            try:
                error_info['camera_id'] = self.camera_id
                self.on_error_callback(error_info)
            except Exception as cb_e:
                logger.error(f"[{self.camera_id}] 错误回调执行失败: {str(cb_e)}")
    
    def _is_capture_healthy(self) -> bool:
        """检查视频捕获是否健康
        
        Returns:
            bool: 视频捕获是否健康
        """
        if self.cap is None or not self.cap.isOpened():
            return False
        
        # 检查连续错误计数
        if self.consecutive_errors > 5:
            return False
        
        return True
    
    def _is_queue_backed_up(self) -> bool:
        """检查队列是否积压
        
        Returns:
            bool: 队列是否积压
        """
        # 如果队列接近满，认为存在积压
        return self.frame_queue.qsize() >= self.frame_queue.maxsize * 0.8
    
    def _calculate_error_rate(self) -> float:
        """计算错误率
        
        Returns:
            float: 错误率
        """
        total_operations = self.stats['frames_processed'] + self.stats['total_errors']
        if total_operations == 0:
            return 0.0
        
        return self.stats['total_errors'] / total_operations
    
    def _should_recover(self) -> bool:
        """判断是否需要执行恢复操作
        
        Returns:
            bool: 是否需要恢复
        """
        if not self.auto_recover or self.is_recovering:
            return False
        
        # 检查是否处于错误状态
        if self.status == 'error':
            return True
        
        # 检查健康状态
        if self.health_status == 'critical':
            return True
        
        # 检查连续错误
        if self.consecutive_errors > 3:
            return True
        
        # 检查恢复冷却时间
        if self.last_recovery_attempt:
            cooldown_remaining = self.recovery_cooldown - \
                               (datetime.now() - self.last_recovery_attempt).total_seconds()
            if cooldown_remaining > 0:
                return False
        
        return False
    
    def _attempt_recovery(self, failed_method=None):
        """尝试从失败中恢复 - 增强版
        
        Args:
            failed_method: 失败的方法名（可选）
            
        Returns:
            bool: 恢复是否成功
        """
        if self.is_recovering:
            logger.warning(f"[{self.camera_id}] 恢复操作已经在进行中")
            return False
        
        self.is_recovering = True
        self.stats['recovery_attempts'] = self.stats.get('recovery_attempts', 0) + 1
        self.last_recovery_attempt = datetime.now()
        logger.info(f"[{self.camera_id}] 开始执行恢复操作，尝试次数: {self.stats['recovery_attempts']}, 失败方法: {failed_method}")
        
        try:
            recovery_start_time = time.time()
            
            # 暂停当前操作，避免频繁重启
            time.sleep(1.0)
            
            # 停止当前操作
            if hasattr(self, '_stop_processing'):
                self._stop_processing()
            
            # 清理资源
            if hasattr(self, '_cleanup_resources'):
                self._cleanup_resources()
            
            # 清理队列
            if hasattr(self, 'frame_queue') and hasattr(self, '_clear_queue_except_latest'):
                self._clear_queue_except_latest(self.frame_queue, keep_count=0)
                if hasattr(self, 'processed_frame_queue'):
                    self._clear_queue_except_latest(self.processed_frame_queue, keep_count=0)
            
            # 重置内部状态
            if hasattr(self, 'tracks'):
                self.tracks = []
            
            # 通知可能需要重启的组件
            if hasattr(self, 'detection_engine') and hasattr(self.detection_engine, 'reset'):
                try:
                    self.detection_engine.reset()
                    logger.info(f"[{self.camera_id}] 检测器已重置")
                except Exception as e:
                    logger.error(f"[{self.camera_id}] 重置检测器失败: {str(e)}")
            
            # 增强的恢复逻辑
            recovery_success = False
            
            # 检查是否有特定方法需要恢复
            if failed_method == '_capture_loop':
                recovery_success = self._recover_capture()
            elif failed_method == '_process_loop':
                recovery_success = self._recover_processing()
            else:
                # 先尝试恢复视频捕获
                if not recovery_success and hasattr(self, '_is_capture_healthy') and not self._is_capture_healthy():
                    recovery_success = self._recover_capture()
                # 如果还不成功，尝试其他恢复策略
                if not recovery_success:
                    if hasattr(self, '_recover_full'):
                        recovery_success = self._recover_full()
                    else:
                        recovery_success = self._recover_basic()
            
            if recovery_success:
                logger.info(f"[{self.camera_id}] 恢复操作成功")
                self.stats['successful_recoveries'] = self.stats.get('successful_recoveries', 0) + 1
                if hasattr(self, 'consecutive_errors'):
                    self.consecutive_errors = 0
                if hasattr(self, 'health_status'):
                    self.health_status = 'healthy'
                
                # 重新启动处理
                if hasattr(self, '_start_processing'):
                    self._start_processing()
            else:
                logger.error(f"[{self.camera_id}] 恢复操作失败")
                
                # 检查是否超过最大尝试次数
                max_retry = getattr(self, 'max_recovery_attempts', 5)
                if self.stats['recovery_attempts'] >= max_retry:
                    logger.critical(f"[{self.camera_id}] 已达到最大恢复尝试次数({max_retry})，将停止服务")
                    self.stop()
            
            logger.info(f"[{self.camera_id}] 恢复操作完成，耗时: {time.time() - recovery_start_time:.2f}秒")
            return recovery_success
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 恢复过程中发生异常: {str(e)}")
            logger.debug(f"[{self.camera_id}] 恢复详细错误: {traceback.format_exc()}")
            return False
        
        finally:
            self.is_recovering = False
            
    def _recover_capture(self) -> bool:
        """恢复视频捕获功能
        
        Returns:
            bool: 恢复是否成功
        """
        try:
            logger.info(f"[{self.camera_id}] 开始恢复视频捕获")
            
            # 释放现有捕获资源
            if hasattr(self, '_cap') and self._cap:
                try:
                    self._cap.release()
                    self._cap = None
                    logger.info(f"[{self.camera_id}] 已释放旧的视频捕获资源")
                except Exception as e:
                    logger.error(f"[{self.camera_id}] 释放视频捕获资源时出错: {str(e)}")
            
            # 强制进行垃圾回收
            gc.collect()
            
            # 重置捕获状态
            if hasattr(self, '_capture_fail_count'):
                self._capture_fail_count = 0
            
            # 重新初始化视频捕获
            max_retry = 3
            for attempt in range(max_retry):
                try:
                    logger.info(f"[{self.camera_id}] 尝试重新初始化视频捕获 (尝试 {attempt + 1}/{max_retry})")
                    
                    # 检查是否有初始化捕获方法
                    init_success = False
                    if hasattr(self, '_initialize_capture'):
                        init_success = self._initialize_capture()
                    elif hasattr(self, 'initialize_capture'):
                        init_success = self.initialize_capture()
                    
                    # 验证视频捕获是否正常工作
                    if (hasattr(self, '_cap') and self._cap and self._cap.isOpened()) or init_success:
                        # 尝试读取一帧以确认
                        if hasattr(self, '_cap') and self._cap:
                            ret, _ = self._cap.read()
                            if ret or init_success:
                                logger.info(f"[{self.camera_id}] 视频捕获初始化成功")
                                return True
                except Exception as e:
                    logger.error(f"[{self.camera_id}] 重新初始化视频捕获失败: {str(e)}")
                    time.sleep(1.0)
            
            logger.error(f"[{self.camera_id}] 所有恢复视频捕获的尝试都失败了")
            return False
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 恢复视频捕获过程中发生未预期异常: {str(e)}")
            logger.debug(f"[{self.camera_id}] 恢复详细错误: {traceback.format_exc()}")
            # 调用错误处理方法通知系统
            if hasattr(self, '_handle_error'):
                self._handle_error(e, 'capture_recovery_failure')
            return False
    
    def _recover_full(self) -> bool:
        """执行完整的系统恢复
        
        Returns:
            bool: 是否恢复成功
        """
        logger.info(f"[{self.camera_id}] 执行完整系统恢复")
        
        try:
            # 完全重置状态
            self.status = 'inactive'
            self.health_status = 'unknown'
            self.last_error = None
            
            # 强制垃圾回收
            gc.collect()
            
            # 重新初始化
            return self.initialize(self.detection_engine, self.behavior_analyzer)
        
        except Exception as e:
            logger.error(f"[{self.camera_id}] 完整恢复失败: {str(e)}")
            # 调用错误处理方法通知系统
            if hasattr(self, '_handle_error'):
                self._handle_error(e, 'recovery_failure')
            return False
    
    def _perform_diagnosis(self):
        """执行详细的系统诊断"""
        logger.info(f"[{self.camera_id}] 执行系统诊断")
        self.last_diagnosis = datetime.now()
        
        diagnosis_report = {
            'camera_id': self.camera_id,
            'timestamp': datetime.now().isoformat(),
            'status': self.status,
            'health_status': self.health_status,
            'capture_status': 'connected' if self._is_capture_healthy() else 'disconnected',
            'queue_status': {
                'frame_queue': self.frame_queue.qsize(),
                'frame_queue_max': self.frame_queue.maxsize,
                'processed_frame_queue': self.processed_frame_queue.qsize()
            },
            'statistics': copy.deepcopy(self.stats)
        }
        
        # 记录诊断报告
        logger.debug(f"[{self.camera_id}] 诊断报告: {diagnosis_report}")
        
        # 清理过期的处理时间记录
        if len(self.stats['processing_times']) > 100:
            self.stats['processing_times'] = self.stats['processing_times'][-100:]
    
    def _cleanup_resources(self):
        """清理系统资源和定期维护"""
        try:
            logger.info(f"[{self.camera_id}] 清理系统资源")
            
            # 清空队列
            if hasattr(self, '_clear_queues'):
                self._clear_queues()
            
            # 释放视频捕获
            if hasattr(self, 'cap') and self.cap is not None:
                try:
                    self.cap.release()
                    self.cap = None
                    logger.info(f"[{self.camera_id}] 视频捕获资源已释放")
                except Exception as e:
                    logger.error(f"[{self.camera_id}] 释放视频捕获失败: {str(e)}")
            
            # 清理统计数据，避免内存泄漏
            if hasattr(self, 'stats'):
                # 限制统计数据长度
                max_history = 1000
                if len(self.stats.get('processing_times', [])) > max_history:
                    self.stats['processing_times'] = self.stats['processing_times'][-max_history:]
                    logger.debug(f"[{self.camera_id}] 已清理旧的处理时间统计数据")
                    
        except Exception as e:
            logger.error(f"[{self.camera_id}] 资源清理失败: {str(e)}")
    
    def _clear_queues(self):
        """清空所有队列并释放相关资源"""
        try:
            logger.info(f"[{self.camera_id}] 开始清空队列")
            
            # 清空帧队列
            cleared_frame_count = 0
            if hasattr(self, 'frame_queue') and self.frame_queue:
                while not self.frame_queue.empty():
                    try:
                        item = self.frame_queue.get_nowait()
                        cleared_frame_count += 1
                        # 释放帧资源
                        if isinstance(item, dict) and 'frame' in item:
                            del item['frame']
                        # 确保标记任务完成
                        try:
                            self.frame_queue.task_done()
                        except:
                            pass
                    except queue.Empty:
                        break
                logger.info(f"[{self.camera_id}] 已清空帧队列，共清理 {cleared_frame_count} 帧")
            
            # 清空已处理帧队列
            cleared_processed_count = 0
            if hasattr(self, 'processed_frame_queue') and self.processed_frame_queue:
                while not self.processed_frame_queue.empty():
                    try:
                        item = self.processed_frame_queue.get_nowait()
                        cleared_processed_count += 1
                        # 释放帧资源
                        if isinstance(item, dict) and 'frame' in item:
                            del item['frame']
                        # 确保标记任务完成
                        try:
                            self.processed_frame_queue.task_done()
                        except:
                            pass
                    except queue.Empty:
                        break
                logger.info(f"[{self.camera_id}] 已清空处理帧队列，共清理 {cleared_processed_count} 帧")
                
            logger.info(f"[{self.camera_id}] 队列清理完成")
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 清空队列时出错: {str(e)}")
    
    def _initialize_capture(self) -> bool:
        """初始化视频捕获
        
        Returns:
            bool: 是否成功
        """
        try:
            # 尝试关闭已有的捕获
            if self.cap is not None:
                self.cap.release()
                self.cap = None
            
            # 创建新的视频捕获
            if isinstance(self.source, str) and self.source.isdigit():
                # 设备ID
                self.cap = cv2.VideoCapture(int(self.source))
            else:
                # RTSP URL或文件路径
                self.cap = cv2.VideoCapture(self.source)
            
            # 检查是否成功打开
            if not self.cap.isOpened():
                logger.error(f"[{self.camera_id}] 无法打开视频源: {self.source}")
                return False
            
            # 获取视频属性
            self.frame_width = int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            self.frame_height = int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            self.fps = self.cap.get(cv2.CAP_PROP_FPS)
            
            # 如果FPS无法获取，设置默认值
            if self.fps <= 0 or self.fps > 120:
                self.fps = 30.0
            
            # 设置视频属性
            if self.config.get('buffer_size', 1):
                self.cap.set(cv2.CAP_PROP_BUFFERSIZE, self.config['buffer_size'])
            
            # 设置编解码器（如果配置了）
            if self.config.get('codec'):
                fourcc = cv2.VideoWriter_fourcc(*self.config['codec'])
                self.cap.set(cv2.CAP_PROP_FOURCC, fourcc)
            
            logger.info(
                f"视频源打开成功: {self.source}, "
                f"分辨率: {self.frame_width}x{self.frame_height}, "
                f"FPS: {self.fps}"
            )
            
            return True
            
        except Exception as e:
            logger.error(f"初始化视频捕获失败: {str(e)}")
            if self.cap is not None:
                self.cap.release()
                self.cap = None
            return False
    
    def start(self) -> bool:
        """启动视频处理器
        
        Returns:
            bool: 是否成功启动
        """
        with self.lock:
            if self.running:
                logger.warning(f"视频处理器已经在运行: {self.camera_id}")
                return True
            
            try:
                logger.info(f"启动视频处理器: {self.camera_id}")
                self.running = True
                self.status = 'starting'
                
                # 清空队列
                while not self.frame_queue.empty():
                    try:
                        self.frame_queue.get_nowait()
                    except queue.Empty:
                        break
                
                while not self.processed_frame_queue.empty():
                    try:
                        self.processed_frame_queue.get_nowait()
                    except queue.Empty:
                        break
                
                # 创建并启动捕获线程
                self.capture_thread = threading.Thread(
                    target=self._capture_loop,
                    name=f"capture-{self.camera_id}",
                    daemon=True
                )
                self.capture_thread.start()
                
                # 创建并启动处理线程
                self.process_thread = threading.Thread(
                    target=self._process_loop,
                    name=f"process-{self.camera_id}",
                    daemon=True
                )
                self.process_thread.start()
                
                # 等待启动
                time.sleep(0.1)
                
                if not self.capture_thread.is_alive() or not self.process_thread.is_alive():
                    logger.error(f"视频处理器线程启动失败: {self.camera_id}")
                    self.stop()
                    return False
                
                self.status = 'active'
                
                # 启动监控线程
                if hasattr(self, '_monitor_enabled') and self._monitor_enabled:
                    self._should_stop_monitor = False
                    self.monitor_thread = threading.Thread(
                        target=self._monitor_system,
                        name=f"monitor-{self.camera_id}",
                        daemon=True
                    )
                    self.monitor_thread.start()
                    logger.info(f"监控线程启动: {self.camera_id}")
                
                logger.info(f"视频处理器启动成功: {self.camera_id}")
                return True
                
            except Exception as e:
                logger.error(f"启动视频处理器失败: {str(e)}")
                self.last_error = str(e)
                self.status = 'error'
                
                # 调用统一错误处理方法
                if hasattr(self, '_handle_error'):
                    self._handle_error(e, 'start_failure')
                
                self.stop()
                return False
    
    def stop(self) -> bool:
        """停止视频处理器
        
        Returns:
            bool: 是否成功停止
        """
        with self.lock:
            if not self.running:
                logger.debug(f"视频处理器已经停止: {self.camera_id}")
                return True
            
            # 记录停止开始时间
            stop_start_time = time.time()
            capture_thread_timed_out = False
            process_thread_timed_out = False
            monitor_thread_timed_out = False
            
            try:
                logger.info(f"开始停止视频处理器: {self.camera_id}")
                self.status = 'stopping'
                self.running = False
                
                # 通知所有线程停止处理
                try:
                    # 设置暂停标志，防止新的帧被处理
                    if hasattr(self, '_paused'):
                        self._paused = True
                    
                    # 停止监控线程
                    if hasattr(self, '_should_stop_monitor'):
                        self._should_stop_monitor = True
                        
                    logger.debug(f"已设置停止标志: {self.camera_id}")
                except Exception as e:
                    logger.error(f"设置停止标志时出错: {str(e)}")
                
                # 等待捕获线程结束，带有超时和强制中断机制
                if self.capture_thread and self.capture_thread.is_alive():
                    logger.debug(f"等待捕获线程结束: {self.camera_id}")
                    try:
                        # 尝试温和地等待线程结束
                        self.capture_thread.join(timeout=3.0)
                        
                        # 如果线程还在运行，添加一个空帧到队列以帮助线程退出
                        if self.capture_thread.is_alive():
                            logger.warning(f"捕获线程仍在运行，尝试唤醒: {self.camera_id}")
                            try:
                                # 添加一个终止信号帧
                                self.frame_queue.put({'terminate': True}, block=False)
                            except Exception as queue_e:
                                logger.warning(f"无法添加终止信号到队列: {str(queue_e)}")
                            
                            # 再次等待
                            self.capture_thread.join(timeout=2.0)
                            
                            if self.capture_thread.is_alive():
                                capture_thread_timed_out = True
                                logger.warning(f"捕获线程未能正常结束: {self.camera_id}")
                        else:
                            logger.debug(f"捕获线程已正常结束: {self.camera_id}")
                    except Exception as e:
                        logger.error(f"等待捕获线程时出错: {str(e)}")
                
                # 等待处理线程结束，带有超时和强制中断机制
                if self.process_thread and self.process_thread.is_alive():
                    logger.debug(f"等待处理线程结束: {self.camera_id}")
                    try:
                        # 尝试温和地等待线程结束
                        self.process_thread.join(timeout=3.0)
                        
                        # 如果线程还在运行，添加一个空帧到队列以帮助线程退出
                        if self.process_thread.is_alive():
                            logger.warning(f"处理线程仍在运行，尝试唤醒: {self.camera_id}")
                            try:
                                # 添加一个终止信号帧
                                self.frame_queue.put({'terminate': True}, block=False)
                            except Exception as queue_e:
                                logger.warning(f"无法添加终止信号到队列: {str(queue_e)}")
                            
                            # 再次等待
                            self.process_thread.join(timeout=2.0)
                            
                            if self.process_thread.is_alive():
                                process_thread_timed_out = True
                                logger.warning(f"处理线程未能正常结束: {self.camera_id}")
                        else:
                            logger.debug(f"处理线程已正常结束: {self.camera_id}")
                    except Exception as e:
                        logger.error(f"等待处理线程时出错: {str(e)}")
                
                # 等待监控线程结束
                if hasattr(self, 'monitor_thread') and self.monitor_thread is not None and self.monitor_thread.is_alive():
                    try:
                        logger.debug(f"等待监控线程结束: {self.camera_id}")
                        self.monitor_thread.join(timeout=2.0)
                        if self.monitor_thread.is_alive():
                            monitor_thread_timed_out = True
                            logger.warning(f"监控线程停止超时: {self.camera_id}")
                        else:
                            logger.debug(f"监控线程已正常结束: {self.camera_id}")
                    except Exception as e:
                        logger.error(f"等待监控线程结束时出错: {str(e)}")
                
                # 释放视频捕获资源
                try:
                    if hasattr(self, 'cap') and self.cap is not None:
                        logger.debug(f"释放视频捕获资源: {self.camera_id}")
                        self.cap.release()
                        self.cap = None
                        logger.debug(f"视频捕获资源已释放: {self.camera_id}")
                except Exception as e:
                    logger.error(f"释放视频捕获资源时出错: {str(e)}", exc_info=True)
                
                # 清空队列，防止资源泄漏
                # 清理帧队列
                try:
                    queue_size = self.frame_queue.qsize()
                    items_cleared = 0
                    max_clears = 1000  # 最多清理1000个项目
                    
                    while not self.frame_queue.empty() and items_cleared < max_clears:
                        try:
                            self.frame_queue.get_nowait()
                            items_cleared += 1
                        except queue.Empty:
                            break
                    
                    remaining = self.frame_queue.qsize()
                    logger.info(f"帧队列清理完成: {self.camera_id}, 已清理: {items_cleared}/{queue_size}, 剩余: {remaining}")
                    
                except Exception as e:
                    logger.error(f"清空帧队列时出错: {str(e)}")
                
                # 清理已处理帧队列
                try:
                    processed_queue_size = self.processed_frame_queue.qsize()
                    processed_items_cleared = 0
                    max_clears = 1000  # 最多清理1000个项目
                    
                    while not self.processed_frame_queue.empty() and processed_items_cleared < max_clears:
                        try:
                            self.processed_frame_queue.get_nowait()
                            processed_items_cleared += 1
                        except queue.Empty:
                            break
                    
                    processed_remaining = self.processed_frame_queue.qsize()
                    logger.info(f"已处理帧队列清理完成: {self.camera_id}, 已清理: {processed_items_cleared}/{processed_queue_size}, 剩余: {processed_remaining}")
                    
                except Exception as e:
                    logger.error(f"清空已处理帧队列时出错: {str(e)}")
                
                # 释放可能的其他资源
                try:
                    # 释放跟踪器资源
                    if hasattr(self, 'tracker') and self.tracker is not None:
                        # 如果跟踪器有stop方法，调用它
                        if hasattr(self.tracker, 'stop') and callable(self.tracker.stop):
                            self.tracker.stop()
                        self.tracker = None
                        logger.debug(f"跟踪器资源已释放: {self.camera_id}")
                    
                    # 释放检测器资源
                    if hasattr(self, '_detector') and self._detector is not None:
                        # 如果检测器有close或release方法，调用它
                        if hasattr(self._detector, 'close') and callable(self._detector.close):
                            self._detector.close()
                        elif hasattr(self._detector, 'release') and callable(self._detector.release):
                            self._detector.release()
                        self._detector = None
                        logger.debug(f"检测器资源已释放: {self.camera_id}")
                    
                    # 释放场景管理器资源
                    if hasattr(self, 'scene_manager') and self.scene_manager is not None:
                        # 如果场景管理器有close或release方法，调用它
                        if hasattr(self.scene_manager, 'close') and callable(self.scene_manager.close):
                            self.scene_manager.close()
                        elif hasattr(self.scene_manager, 'release') and callable(self.scene_manager.release):
                            self.scene_manager.release()
                        self.scene_manager = None
                        logger.debug(f"场景管理器资源已释放: {self.camera_id}")
                except Exception as e:
                    logger.error(f"释放额外资源时出错: {str(e)}")
                
                # 更新统计信息
                stop_duration = time.time() - stop_start_time
                self.stats['stop_duration'] = stop_duration
                self.stats['last_stop_time'] = time.time()
                
                # 检查是否有线程超时
                if capture_thread_timed_out or process_thread_timed_out:
                    self.stats['thread_timeouts'] = self.stats.get('thread_timeouts', 0) + 1
                    logger.warning(f"停止过程中有线程超时: {self.camera_id}, 捕获线程: {capture_thread_timed_out}, 处理线程: {process_thread_timed_out}")
                
                self.status = 'inactive'
                
                # 记录停止完成信息
                logger.info(
                    f"视频处理器停止成功: {self.camera_id}, "
                    f"耗时: {stop_duration:.2f}秒, "
                    f"总处理帧数: {self.frame_count}, "
                    f"错误次数: {self.stats.get('errors', 0)}"
                )
                return True
                
            except Exception as e:
                logger.error(f"停止视频处理器失败: {str(e)}", exc_info=True)
                self.last_error = f"停止失败: {str(e)}"
                self.status = 'error'
                
                # 调用统一错误处理方法
                if hasattr(self, '_handle_error'):
                    self._handle_error(e, 'stop_failure')
                
                # 即使发生异常，也尝试释放基本资源
                try:
                    if hasattr(self, 'cap') and self.cap is not None:
                        self.cap.release()
                        self.cap = None
                except:
                    pass
                
                return False
    
    @exception_handler
    def _capture_loop(self):
        """视频捕获循环 - 优化版"""
        logger.info(f"捕获线程启动: {self.camera_id}")
        self.stats['capture_thread_start_time'] = time.time()
        
        # 初始化统计和状态变量
        reconnect_attempts = 0
        max_reconnect_attempts = self.config.get('max_reconnect_attempts', 5)
        reconnect_delay = self.config.get('reconnect_delay', 2.0)
        last_reconnect_time = 0
        capture_failures = 0
        consecutive_failures = 0  # 新增：连续失败计数
        frame_count = 0
        frames_captured = 0
        last_fps_update_time = time.time()
        last_capture_time = 0
        
        # 获取队列配置
        max_queue_size = self.config.get('max_queue_size', 50)
        allow_queue_override = self.config.get('allow_queue_override', True)
        queue_warning_threshold = int(max_queue_size * 0.8)  # 队列警告阈值（80%）
        
        # 性能监控变量
        performance_stats = {
            'total_capture_time': 0,
            'total_frames_processed': 0,
            'total_resize_time': 0,
            'last_performance_update': time.time()
        }
        
        # 动态FPS适应配置
        adaptive_fps_enabled = self.config.get('adaptive_fps', True)
        min_adaptive_fps = self.config.get('min_adaptive_fps', 5)
        max_adaptive_fps = self.config.get('max_adaptive_fps', 30)
        target_queue_size = int(max_queue_size * 0.5)  # 目标队列大小（50%）
        current_adaptive_fps = self.fps
        
        while self.running:
            try:
                # 检查是否需要暂停捕获
                if hasattr(self, '_paused') and self._paused:
                    time.sleep(0.1)
                    continue
                
                current_time = time.time()
                
                # 检查视频捕获是否正常，带有限流保护
                if self.cap is None or not self.cap.isOpened():
                    # 重连限流
                    if current_time - last_reconnect_time > reconnect_delay:
                        logger.warning(f"视频源断开，尝试重连: {self.camera_id}, 尝试: {reconnect_attempts+1}")
                        
                        if reconnect_attempts < max_reconnect_attempts:
                            if self._initialize_capture():
                                logger.info(f"重连成功: {self.camera_id}")
                                reconnect_attempts = 0
                                frame_count = 0
                                capture_failures = 0
                                consecutive_failures = 0
                                last_capture_time = current_time
                                # 重置冷却时间
                                reconnect_delay = self.config.get('reconnect_delay', 2.0)
                                # 重置动态FPS
                                current_adaptive_fps = self.fps
                            else:
                                reconnect_attempts += 1
                                # 动态增加重连延迟
                                reconnect_delay = min(reconnect_delay * 1.5, 30.0)  # 最多30秒
                                logger.warning(f"重连失败，增加冷却时间至: {reconnect_delay:.1f}s")
                        else:
                            logger.error(f"达到最大重连次数，停止重连: {self.camera_id}")
                            self.last_error = "无法重连到视频源"
                            self.status = 'error'
                            # 触发错误回调
                            self._handle_error(Exception("达到最大重连次数"), 'capture_failure')
                            break
                        
                        last_reconnect_time = current_time
                    else:
                        # 还在冷却期内，短暂等待
                        time.sleep(0.1)
                    continue
                
                # 读取帧，增加读取超时和重试机制
                ret = False
                frame = None
                retry_count = 0
                max_retries = self.config.get('read_retry_count', 3)
                read_success = False
                
                # 帧读取开始时间
                read_start_time = time.time()
                
                while retry_count < max_retries and not read_success:
                    retry_count += 1
                    capture_start_time = time.time()
                    
                    try:
                        # 添加超时控制
                        timeout = 0.5  # 500ms超时
                        if hasattr(self, 'cap') and hasattr(self.cap, 'set'):
                            # 设置OpenCV读取超时（仅在支持的情况下）
                            try:
                                self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)  # 减少缓冲区大小以降低延迟
                            except:
                                pass
                        
                        ret, frame = self.cap.read()
                        
                        # 检查帧是否成功读取并有效
                        if ret and frame is not None and frame.size > 0 and len(frame.shape) >= 2:
                            # 进一步验证帧质量
                            if frame.shape[0] > 0 and frame.shape[1] > 0:
                                read_success = True
                                last_capture_time = capture_start_time
                                consecutive_failures = 0  # 重置连续失败计数
                            else:
                                logger.warning(f"获取到无效帧尺寸(尝试 {retry_count}/{max_retries}): {self.camera_id}, 形状: {frame.shape if frame is not None else 'None'}")
                        else:
                            logger.warning(f"获取到无效帧(尝试 {retry_count}/{max_retries}): {self.camera_id}")
                            consecutive_failures += 1
                            
                            if retry_count < max_retries:
                                time.sleep(0.05)  # 短暂等待后重试
                    except Exception as read_e:
                        logger.error(f"读取帧异常(尝试 {retry_count}/{max_retries}): {str(read_e)}")
                        consecutive_failures += 1
                        if retry_count < max_retries:
                            time.sleep(0.05)
                
                # 处理读取失败的情况
                if not read_success:
                    capture_failures += 1
                    consecutive_failures += 1
                    
                    # 更新统计
                    self.stats['capture_failures'] = self.stats.get('capture_failures', 0) + 1
                    self.stats['consecutive_failures'] = consecutive_failures
                    
                    # 连续失败策略
                    if consecutive_failures >= 3:
                        logger.warning(f"连续读取失败 {consecutive_failures} 次: {self.camera_id}")
                    elif consecutive_failures >= 10:
                        logger.error(f"严重错误: 连续读取失败 {consecutive_failures} 次: {self.camera_id}")
                    
                    # 触发重连机制
                    if consecutive_failures >= 5 and (current_time - last_reconnect_time > reconnect_delay):
                        logger.warning(f"连续失败超过阈值，触发重连: {self.camera_id}")
                        
                        # 优雅地释放资源
                        try:
                            if self.cap is not None:
                                self.cap.release()
                                self.cap = None
                        except Exception as release_e:
                            logger.error(f"释放捕获资源时出错: {str(release_e)}")
                        
                        last_reconnect_time = current_time
                        reconnect_attempts = 0
                        capture_failures = 0
                        consecutive_failures = 0
                    
                    # 基于失败次数的动态休眠
                    sleep_time = min(0.05 + (0.01 * consecutive_failures), 0.5)
                    time.sleep(sleep_time)
                    continue
                
                # 重置失败计数
                capture_failures = 0
                consecutive_failures = 0
                
                # 增加帧计数
                frame_count += 1
                
                # 帧间隔处理
                if frame_count % self.frame_interval != 0:
                    continue
                
                # 计算捕获性能
                capture_time = time.time() - read_start_time
                performance_stats['total_capture_time'] += capture_time
                performance_stats['total_frames_processed'] += 1
                
                # 调整分辨率（如果配置了）
                if self.resolution[0] > 0 and self.resolution[1] > 0:
                    resize_start_time = time.time()
                    try:
                        # 使用高质量的插值方法
                        interpolation = cv2.INTER_AREA if (frame.shape[0] > self.resolution[1] or frame.shape[1] > self.resolution[0]) else cv2.INTER_CUBIC
                        frame = cv2.resize(frame, self.resolution, interpolation=interpolation)
                        performance_stats['total_resize_time'] += time.time() - resize_start_time
                    except Exception as resize_e:
                        logger.error(f"调整分辨率失败: {str(resize_e)}")
                        # 记录失败但继续处理
                        self.stats['resize_failures'] = self.stats.get('resize_failures', 0) + 1
                
                # 获取当前时间
                timestamp = current_time
                self.frame_count += 1
                
                # 创建帧数据，增加额外的元数据
                frame_data = {
                    'camera_id': self.camera_id,
                    'frame': frame,
                    'timestamp': timestamp,
                    'frame_id': self.frame_count,
                    'capture_time': last_capture_time,
                    'processing_metadata': {
                        'read_attempts': retry_count,
                        'capture_duration_ms': capture_time * 1000
                    }
                }
                
                # 回调原始帧
                if self.on_frame_callback:
                    try:
                        self.on_frame_callback(frame_data)
                    except Exception as e:
                        logger.error(f"原始帧回调错误: {str(e)}")
                        # 记录回调错误
                        self.stats['callback_errors'] = self.stats.get('callback_errors', 0) + 1
                
                # 队列管理策略 - 优化版
                try:
                    current_queue_size = self.frame_queue.qsize()
                    
                    # 队列状态监控
                    if current_queue_size >= queue_warning_threshold:
                        logger.warning(f"队列接近容量上限: {self.camera_id}, 当前大小: {current_queue_size}/{max_queue_size}")
                    
                    # 队列管理策略：
                    # 1. 如果队列未满，直接放入
                    if current_queue_size < max_queue_size:
                        self.frame_queue.put(frame_data, block=False)
                        frames_captured += 1
                    else:
                        if allow_queue_override:
                            # 智能清理策略：根据队列状态决定清理比例
                            if current_queue_size > max_queue_size * 1.5:  # 严重积压
                                clear_ratio = 0.7  # 清理70%
                            else:
                                clear_ratio = 0.5  # 清理50%
                            
                            old_frames_count = max(1, int(current_queue_size * clear_ratio))
                            cleared_count = 0
                            
                            for _ in range(old_frames_count):
                                try:
                                    if not self.frame_queue.empty():
                                        self.frame_queue.get_nowait()
                                        cleared_count += 1
                                except queue.Empty:
                                    break
                            
                            # 放入新帧
                            self.frame_queue.put(frame_data, block=False)
                            frames_captured += 1
                            logger.debug(f"队列已满，清理 {cleared_count} 帧后放入新帧: {self.camera_id}")
                            # 记录队列清理事件
                            self.stats['queue_clears'] = self.stats.get('queue_clears', 0) + 1
                        else:
                            logger.warning(f"帧队列已满且不允许覆盖，丢弃帧: {self.camera_id}")
                            # 记录丢弃的帧
                            self.stats['dropped_frames'] = self.stats.get('dropped_frames', 0) + 1
                except Exception as e:
                    logger.error(f"帧队列操作错误: {str(e)}")
                    # 记录队列错误
                    self.stats['queue_errors'] = self.stats.get('queue_errors', 0) + 1
                
                # 动态FPS适应
                if adaptive_fps_enabled and self.fps > 0:
                    # 获取当前队列大小
                    current_queue_size = self.frame_queue.qsize()
                    
                    # 根据队列状态调整FPS
                    if current_queue_size > target_queue_size * 1.5 and current_adaptive_fps > min_adaptive_fps:
                        # 队列积压，降低FPS
                        current_adaptive_fps = max(min_adaptive_fps, current_adaptive_fps * 0.9)
                        if self.frame_count % 100 == 0:  # 避免频繁日志
                            logger.debug(f"队列积压，降低捕获FPS至: {current_adaptive_fps:.1f}fps")
                    elif current_queue_size < target_queue_size * 0.5 and current_adaptive_fps < max_adaptive_fps:
                        # 队列空闲，提高FPS
                        current_adaptive_fps = min(max_adaptive_fps, current_adaptive_fps * 1.1)
                        if self.frame_count % 100 == 0:  # 避免频繁日志
                            logger.debug(f"队列空闲，提高捕获FPS至: {current_adaptive_fps:.1f}fps")
                    
                    # 使用动态FPS限制捕获速度
                    target_interval = 1.0 / current_adaptive_fps
                    elapsed = time.time() - capture_start_time
                    sleep_time = max(0, target_interval - elapsed)
                    
                    # 智能休眠：如果处理速度足够快就休眠，否则不休眠
                    if sleep_time > 0.001:  # 只在需要休眠超过1ms时才执行
                        time.sleep(sleep_time)
                elif self.fps > 0:
                    # 固定FPS模式
                    target_interval = 1.0 / self.fps
                    elapsed = time.time() - capture_start_time
                    sleep_time = max(0, target_interval - elapsed)
                    
                    if sleep_time > 0.001:
                        time.sleep(sleep_time)
                
                # 更新FPS统计
                if current_time - last_fps_update_time > 5.0:  # 每5秒更新一次
                    actual_fps = frames_captured / (current_time - last_fps_update_time)
                    self.stats['capture_fps'] = actual_fps
                    self.stats['current_queue_size'] = self.frame_queue.qsize()
                    self.stats['current_adaptive_fps'] = current_adaptive_fps
                    
                    # 更新性能统计
                    avg_capture_time = performance_stats['total_capture_time'] / max(1, performance_stats['total_frames_processed'])
                    self.stats['avg_capture_time_ms'] = avg_capture_time * 1000
                    
                    # 根据FPS级别输出不同级别的日志
                    if actual_fps < 5.0:
                        logger.warning(f"捕获FPS过低: {self.camera_id}, {actual_fps:.1f}fps, 目标: {self.fps}fps")
                    elif abs(actual_fps - self.fps) > self.fps * 0.3:
                        logger.info(f"捕获FPS与目标偏差较大: {self.camera_id}, 当前: {actual_fps:.1f}fps, 目标: {self.fps}fps")
                    else:
                        logger.debug(f"捕获统计更新: {self.camera_id}, FPS: {actual_fps:.1f}, 队列: {self.frame_queue.qsize()}, 平均捕获时间: {avg_capture_time*1000:.2f}ms")
                    
                    last_fps_update_time = current_time
                    frames_captured = 0
                    
                    # 重置性能统计
                    performance_stats = {
                        'total_capture_time': 0,
                        'total_frames_processed': 0,
                        'total_resize_time': 0,
                        'last_performance_update': current_time
                    }
                
                # 定期检查捕获状态
                if self.frame_count % 100 == 0:
                    logger.debug(f"捕获状态检查: {self.camera_id}, 帧索引: {self.frame_count}, 队列: {self.frame_queue.qsize()}, 状态: 正常")
                
                # 长时间未成功捕获的保护
                if last_capture_time and (current_time - last_capture_time > 10):
                    logger.warning(f"长时间未成功捕获帧: {self.camera_id}, 上次成功时间: {current_time - last_capture_time:.1f}s")
                    # 尝试重置捕获
                    try:
                        if self.cap is not None:
                            self.cap.release()
                            self.cap = None
                        last_reconnect_time = current_time
                        consecutive_failures = 0
                    except Exception as reset_e:
                        logger.error(f"重置捕获资源时出错: {str(reset_e)}")
                    
                    # 记录长时间无捕获事件
                    self.stats['long_no_capture_events'] = self.stats.get('long_no_capture_events', 0) + 1
                    
            except Exception as e:
                logger.error(f"捕获循环错误: {str(e)}", exc_info=True)
                self.last_error = f"捕获循环错误: {str(e)}"
                
                # 调用统一错误处理方法
                self._handle_error(e, 'capture_loop_exception')
                
                # 更新失败计数
                capture_failures += 1
                consecutive_failures += 1
                
                # 尝试重新连接，但带限流保护
                current_time = time.time()
                if current_time - last_reconnect_time > reconnect_delay:
                    logger.warning(f"捕获异常后尝试重连: {self.camera_id}")
                    # 优雅地重置捕获
                    try:
                        if self.cap is not None:
                            self.cap.release()
                    except Exception as release_e:
                        logger.error(f"释放捕获资源时出错: {str(release_e)}")
                    finally:
                        self.cap = None
                    
                    last_reconnect_time = current_time
                    consecutive_failures = 0
                
                # 基于错误次数的动态休眠
                sleep_time = min(0.1 * capture_failures, 1.0)  # 失败越多，休眠时间越长，但最多1秒
                time.sleep(sleep_time)
        
        # 释放视频捕获资源 - 加强版
        try:
            logger.info(f"开始释放视频捕获资源: {self.camera_id}")
            
            # 清理队列
            try:
                while not self.frame_queue.empty():
                    self.frame_queue.get_nowait()
            except:
                pass
            
            # 释放捕获设备
            if self.cap is not None:
                try:
                    self.cap.release()
                    self.cap = None
                    logger.info(f"视频捕获设备释放成功: {self.camera_id}")
                except Exception as release_e:
                    logger.error(f"释放捕获设备时出错: {str(release_e)}")
            
            # 记录最终统计
            self.stats['capture_thread_ended'] = True
            self.stats['last_capture_thread_end_time'] = time.time()
            
            logger.info(f"捕获线程结束: {self.camera_id}, 总处理帧数: {self.frame_count}")
        except Exception as e:
            logger.error(f"捕获线程清理阶段错误: {str(e)}")
            
        logger.info(f"捕获线程完全结束: {self.camera_id}")
        
    # 使用上面定义的_handle_error方法，此处不再重复定义
    # 原有的_handle_error方法已被移除，统一使用更完整的版本
    
    @exception_handler
    def _process_loop(self):
        """视频处理循环 - 优化版本，包含更健壮的错误处理和性能监控"""
        logger.info(f"处理线程启动: {self.camera_id}")
        self.stats['process_thread_start_time'] = time.time()
        
        # 初始化性能监控和错误跟踪变量
        last_stats_time = time.time()
        frames_since_stats = 0
        error_count = 0
        consecutive_errors = 0
        last_error_time = 0
        last_recovery_time = 0
        resource_warning_count = 0
        
        # 动态性能调整参数
        performance_adjustment = {
            'current_scale': 1.0,  # 初始缩放因子
            'min_scale': 0.5,      # 最小缩放因子
            'max_scale': 1.0,      # 最大缩放因子
            'adjustment_step': 0.1 # 调整步长
        }
        
        # 正确的结构开始
        try:
            while self.running:
                # 方法主体内容继续...
                # 检查是否需要暂停处理
                if hasattr(self, '_paused') and self._paused:
                    logger.debug(f"处理线程暂停: {self.camera_id}")
                    time.sleep(0.1)
                    continue
                
                # 系统资源监控 - 每5秒检查一次
                current_time = time.time()
                if current_time - last_stats_time >= 5.0:
                    self._monitor_system_resources()
                    last_stats_time = current_time
                
                # 从队列获取帧，带有超时机制
                try:
                    # 动态调整超时时间基于系统负载
                    timeout_adjusted = min(0.5 / performance_adjustment['current_scale'], 1.0)
                    frame_data = self.frame_queue.get(timeout=timeout_adjusted)
                    
                    # 重置连续错误计数
                    consecutive_errors = 0
                    
                    # 输入验证 - 增强版
                    if not isinstance(frame_data, dict):
                        logger.warning(f"无效的帧数据格式: {self.camera_id}, 类型: {type(frame_data).__name__}")
                        self.frame_queue.task_done()
                        error_count += 1
                        continue
                        
                    # 检查必要字段
                    if 'timestamp' not in frame_data or 'frame' not in frame_data:
                        missing_fields = []
                        if 'timestamp' not in frame_data:
                            missing_fields.append('timestamp')
                        if 'frame' not in frame_data:
                            missing_fields.append('frame')
                        logger.warning(f"帧数据缺少必要字段: {self.camera_id}, 缺少字段: {', '.join(missing_fields)}")
                        self.frame_queue.task_done()
                        error_count += 1
                        continue
                    
                    # 验证字段类型
                    if not isinstance(frame_data['timestamp'], (int, float)):
                        logger.warning(f"帧时间戳类型无效: {self.camera_id}, 类型: {type(frame_data['timestamp']).__name__}")
                        self.frame_queue.task_done()
                        error_count += 1
                        continue
                    
                    timestamp = frame_data['timestamp']
                    frame = frame_data['frame']
                    
                    # 检查帧是否有效
                    if frame is None or not isinstance(frame, np.ndarray) or frame.size == 0:
                        logger.warning(f"无效的帧内容: {self.camera_id}, 帧大小: {frame.size if frame is not None else 'None'}")
                        self.frame_queue.task_done()
                        error_count += 1
                        continue
                        
                        # 检查帧是否过期
                        frame_age = current_time - timestamp
                        if frame_age > self.max_frame_age:
                            logger.debug(f"跳过过期帧: {self.camera_id}, 帧年龄: {frame_age:.2f}s, 最大允许年龄: {self.max_frame_age}s")
                            self.frame_queue.task_done()
                            
                            # 智能队列管理 - 基于帧年龄动态调整清理策略
                            queue_size = self.frame_queue.qsize()
                            if queue_size > 10:
                                # 队列积压严重时，根据积压程度决定清理策略
                                if queue_size > 20:
                                    logger.warning(f"队列严重积压: {self.camera_id}, 当前队列大小: {queue_size}")
                                    # 清理更多旧帧，保留最新的5帧
                                    self._clear_queue_except_latest(self.frame_queue, keep_count=5)
                                else:
                                    logger.warning(f"队列积压: {self.camera_id}, 当前队列大小: {queue_size}")
                                    self._clear_queue_except_latest(self.frame_queue)
                            continue
                        
                        # 开始处理时间
                        process_start_time = time.time()
                        
                        # 帧复制优化 - 根据性能调整复制策略
                        try:
                            # 仅在需要修改帧时使用深拷贝，否则使用浅拷贝
                            if self.config.get('visualization', True) or self.on_processed_frame_callback:
                                frame_copy = copy.deepcopy(frame_data)
                            else:
                                frame_copy = frame_data.copy()
                                # 对于浅拷贝，需要确保帧数据是独立的
                                if 'frame' in frame_copy:
                                    frame_copy['frame'] = frame.copy()
                        except Exception as e:
                            logger.error(f"复制帧失败: {str(e)}")
                            error_count += 1
                            consecutive_errors += 1
                            self.frame_queue.task_done()
                            continue
                        
                        # 动态性能调整 - 基于系统负载调整处理策略
                        if performance_adjustment['current_scale'] < 1.0:
                            # 降低分辨率以提高性能
                            try:
                                scale_factor = performance_adjustment['current_scale']
                                orig_height, orig_width = frame_copy['frame'].shape[:2]
                                new_width = int(orig_width * scale_factor)
                                new_height = int(orig_height * scale_factor)
                                frame_copy['frame'] = cv2.resize(frame_copy['frame'], (new_width, new_height))
                                frame_copy['resized'] = True
                                frame_copy['resize_scale'] = scale_factor
                            except Exception as e:
                                logger.warning(f"性能优化 - 调整分辨率失败: {str(e)}")
                        
                        # 执行检测 - 增强错误处理和恢复机制
                        detections = []
                        detection_success = False
                        detection_attempts = 0
                        max_detection_attempts = 2  # 最大重试次数
                        
                        while detection_attempts < max_detection_attempts and not detection_success:
                            detection_attempts += 1
                            try:
                                if self.detection_engine is not None:
                                    detections = self.detection_engine.detect(frame_copy['frame'])
                                    if isinstance(detections, list):
                                        frame_copy['detections'] = detections
                                        detection_success = True
                                    else:
                                        logger.warning(f"检测器返回无效格式: {self.camera_id}, 类型: {type(detections).__name__}")
                                        frame_copy['detections'] = []
                                        detection_success = True  # 格式错误但可以继续
                                else:
                                    frame_copy['detections'] = []
                                    detection_success = True
                            except Exception as e:
                                logger.error(f"目标检测错误 (尝试 {detection_attempts}/{max_detection_attempts}): {str(e)}", 
                                           exc_info=detection_attempts == max_detection_attempts)  # 最后一次尝试才记录完整堆栈
                                error_count += 1
                                consecutive_errors += 1
                                
                                # 检测失败后的恢复措施
                                if detection_attempts < max_detection_attempts:
                                    logger.debug(f"尝试恢复检测器: {self.camera_id}")
                                    # 短暂休眠后重试
                                    time.sleep(0.05)
                                else:
                                    frame_copy['detections'] = []
                                    # 通知系统检测器可能需要重启
                                if hasattr(self, '_handle_error'):
                                    self._handle_error(e, 'detection_engine_failure')
                        
                        # 执行场景分析和切换
                        try:
                            if self.scene_manager is not None:
                                # 使用检测结果和帧数据进行场景分析
                                scene_info = {
                                    'camera_id': self.camera_id,
                                    'timestamp': frame_copy['timestamp'],
                                    'frame': frame_copy['frame'],
                                    'detections': frame_copy['detections'],
                                    'tracks': frame_copy['tracks'] if 'tracks' in frame_copy else []
                                }
                                
                                # 执行场景分析并可能触发场景切换
                                current_scene = self.scene_manager.analyze_and_switch(scene_info)
                                
                                # 将当前场景信息添加到帧数据中
                                if current_scene:
                                    frame_copy['current_scene'] = {
                                        'name': current_scene.name,
                                        'priority': current_scene.priority,
                                        'duration': current_scene.duration
                                    }
                        except Exception as e:
                            logger.error(f"场景分析错误: {str(e)}")
                            error_count += 1
                        
                        # 执行跟踪 - 类似检测的增强错误处理
                        tracks = []
                        track_success = False
                        track_attempts = 0
                        max_track_attempts = 2
                        
                        while track_attempts < max_track_attempts and not track_success:
                            track_attempts += 1
                            try:
                                if self.detection_engine is not None and hasattr(self.detection_engine, 'track'):
                                    tracks = self.detection_engine.track(
                                        frame_copy['frame'], 
                                        detections, 
                                        self.camera_id
                                    )
                                    if isinstance(tracks, list):
                                        frame_copy['tracks'] = tracks
                                        if hasattr(self, 'tracks'):
                                            self.tracks = tracks  # 更新当前跟踪
                                        track_success = True
                                    else:
                                        logger.warning(f"跟踪器返回无效格式: {self.camera_id}, 类型: {type(tracks).__name__}")
                                        frame_copy['tracks'] = []
                                        track_success = True
                                else:
                                    frame_copy['tracks'] = []
                                    track_success = True
                            except Exception as e:
                                logger.error(f"目标跟踪错误 (尝试 {track_attempts}/{max_track_attempts}): {str(e)}", 
                                           exc_info=track_attempts == max_track_attempts)
                                error_count += 1
                                consecutive_errors += 1
                                
                                if track_attempts < max_track_attempts:
                                    time.sleep(0.05)
                                else:
                                    frame_copy['tracks'] = []
                        
                        # 执行行为分析 - 增强版
                        behaviors = []
                        try:
                            if self.behavior_analyzer is not None:
                                # 获取当前场景信息
                                current_scene_info = frame_copy.get('current_scene', None)
                                
                                behaviors = self.behavior_analyzer.analyze_behaviors(
                                        self.camera_id,
                                        frame_copy['frame'],
                                        tracks,
                                        frame_copy['timestamp'],
                                        current_scene=current_scene_info
                                    )
                                if isinstance(behaviors, list):
                                    frame_copy['behaviors'] = behaviors
                                else:
                                    logger.warning(f"行为分析器返回无效格式: {self.camera_id}, 类型: {type(behaviors).__name__}")
                                    frame_copy['behaviors'] = []
                            else:
                                frame_copy['behaviors'] = []
                        except Exception as e:
                            logger.error(f"行为分析错误: {str(e)}", exc_info=True)
                            error_count += 1
                            consecutive_errors += 1
                            frame_copy['behaviors'] = []
                        
                        # 生成告警 - 优化版本
                        if behaviors and hasattr(self, 'on_alert_callback') and self.on_alert_callback:
                            try:
                                # 过滤和分组告警，避免短时间内产生过多告警
                                violation_behaviors = [b for b in behaviors if isinstance(b, dict) and b.get('is_violation', False)]
                                
                                if violation_behaviors:
                                    logger.info(f"检测到违规行为: {self.camera_id}, 数量: {len(violation_behaviors)}")
                                    
                                    # 批量处理告警，减少回调开销
                                    for behavior in violation_behaviors:
                                        try:
                                            # 检查告警频率限制
                                            if self._should_trigger_alert(behavior):
                                                self.on_alert_callback({
                                                    'camera_id': self.camera_id,
                                                    'timestamp': frame_copy['timestamp'],
                                                    'behavior': behavior,
                                                    'frame': frame_copy['frame']
                                                })
                                                # 记录告警触发时间
                                                self._record_alert_trigger(behavior)
                                        except Exception as alert_e:
                                            logger.error(f"告警回调执行错误: {str(alert_e)}")
                                            error_count += 1
                            except Exception as e:
                                logger.error(f"告警处理错误: {str(e)}", exc_info=True)
                                error_count += 1
                        
                        # 执行可视化 - 优化版本
                        if self.config.get('visualization', True):
                            try:
                                self._visualize_frame(frame_copy)
                            except Exception as e:
                                logger.error(f"帧可视化错误: {str(e)}")
                                error_count += 1
                                # 可视化失败不影响其他处理流程
                        
                        # 计算处理时间
                        processing_time = time.time() - process_start_time
                        
                        # 更新统计信息 - 增强版
                        frames_since_stats += 1
                        self.stats['processing_times'].append(processing_time)
                        
                        # 限制统计数据长度，避免内存泄漏
                        max_processing_times = self.config.get('max_processing_time_history', 100)
                        if len(self.stats['processing_times']) > max_processing_times:
                            self.stats['processing_times'] = self.stats['processing_times'][-max_processing_times:]
                        
                        # 周期性更新FPS和平均处理时间
                        if current_time - last_stats_time >= 1.0:
                            # 计算更准确的FPS
                            self.stats['fps'] = frames_since_stats / (current_time - last_stats_time)
                            self.stats['avg_processing_time'] = sum(self.stats['processing_times']) / len(self.stats['processing_times']) if self.stats['processing_times'] else 0
                            self.stats['error_count'] = error_count
                            
                            # 动态性能调整 - 基于FPS和处理时间
                            self._adjust_performance(performance_adjustment)
                            
                            # 性能日志 - 分级记录
                            if self.stats['fps'] < 5.0:
                                logger.warning(f"性能警告: {self.camera_id}, FPS: {self.stats['fps']:.1f}, "
                                            f"平均处理时间: {self.stats['avg_processing_time']*1000:.1f}ms, "
                                            f"错误数: {error_count}, "
                                            f"性能缩放: {performance_adjustment['current_scale']:.1f}")
                            elif self.stats['fps'] < 10.0:
                                logger.info(f"性能统计: {self.camera_id}, FPS: {self.stats['fps']:.1f}, "
                                          f"平均处理时间: {self.stats['avg_processing_time']*1000:.1f}ms")
                            else:
                                logger.debug(f"性能统计: {self.camera_id}, FPS: {self.stats['fps']:.1f}")
                            
                            last_stats_time = current_time
                            frames_since_stats = 0
                        
                        # 更新总体统计
                        self.stats['frames_processed'] += 1
                        self.stats['last_frame_time'] = current_time
                        self.stats['processing_time'] = processing_time
                        
                        # 添加到已处理帧队列 - 智能队列管理
                        try:
                            max_processed_queue_size = self.config.get('max_processed_queue_size', 10)
                            queue_size = self.processed_frame_queue.qsize()
                            
                            # 队列管理策略 - 根据队列大小决定保留哪些帧
                            if queue_size >= max_processed_queue_size:
                                # 智能清理 - 分析队列内容，保留更重要的帧
                                self._smart_clean_processed_queue()
                                
                            # 放入队列，使用较短的超时
                            self.processed_frame_queue.put(frame_copy, block=True, timeout=0.1)
                        except queue.Full:
                            try:
                                # 移除最旧的帧
                                self.processed_frame_queue.get_nowait()
                                self.processed_frame_queue.put(frame_copy, block=False)
                            except Exception as e:
                                logger.warning(f"处理帧队列操作错误: {str(e)}")
                                # 释放帧资源，防止内存泄漏
                                if 'frame' in frame_copy:
                                    del frame_copy['frame']
                        except Exception as e:
                            logger.error(f"处理队列操作异常: {str(e)}")
                            # 释放帧资源
                            if 'frame' in frame_copy:
                                del frame_copy['frame']
                        
                        # 回调处理后帧 - 增强错误处理
                        if hasattr(self, 'on_processed_frame_callback') and self.on_processed_frame_callback:
                            try:
                                self.on_processed_frame_callback(frame_copy)
                            except Exception as e:
                                logger.error(f"处理帧回调错误: {str(e)}")
                                error_count += 1
                        
                        # 回调检测结果 - 增强版
                        if hasattr(self, 'on_detection_callback') and self.on_detection_callback and detections:
                            try:
                                # 准备精简的回调数据，减少数据传输
                                callback_data = {
                                    'camera_id': self.camera_id,
                                    'timestamp': frame_copy['timestamp'],
                                    'detections': detections[:100],  # 限制最大检测数量
                                    'tracks': tracks[:100] if tracks else [],
                                    'scene': frame_copy.get('scene', {})  # 添加场景信息
                                }
                                self.on_detection_callback(callback_data)
                            except Exception as e:
                                logger.error(f"检测回调错误: {str(e)}")
                                error_count += 1
                        
                        # 标记任务完成
                        self.frame_queue.task_done()
                        
                    try:
                        # 这里应该是获取队列数据的代码
                        pass
                    except queue.Empty:
                        # 队列为空，智能休眠
                        queue_size = self.frame_queue.qsize()
                        if queue_size > 20:
                            logger.warning(f"队列积压严重，需要优化: {self.camera_id}, 队列大小: {queue_size}")
                            # 激进清理策略
                            self._clear_queue_except_latest(self.frame_queue, keep_count=3)
                        
                        # 动态休眠时间 - 基于系统负载
                        sleep_time = min(0.01 / performance_adjustment['current_scale'], 0.1)
                        time.sleep(sleep_time)
                    except Exception as e:
                        # 处理帧获取和处理过程中的异常
                        logger.error(f"帧处理异常: {str(e)}", exc_info=True)
                        error_count += 1
                        consecutive_errors += 1
                        self.last_error = str(e)
                        
                        # 尝试标记任务完成，避免队列阻塞
                        try:
                            self.frame_queue.task_done()
                        except:
                            pass
                        
                        # 连续错误处理
                        if consecutive_errors >= 5:
                            logger.error(f"连续处理错误达到阈值: {self.camera_id}, 尝试恢复")
                            # 执行恢复操作
                            if current_time - last_recovery_time > 10:  # 每10秒最多恢复一次
                                self._attempt_recovery()
                                last_recovery_time = current_time
                        
                        # 动态休眠 - 基于错误严重程度
                        error_sleep_time = min(0.1 * consecutive_errors, 1.0)
                        time.sleep(error_sleep_time)
                
                    # 错误率过高时触发警告和恢复
                    current_time = time.time()
                    if error_count > 10 and (current_time - last_error_time > 30):
                        logger.warning(f"处理错误率过高: {self.camera_id}, 最近错误数: {error_count}")
                        if hasattr(self, '_handle_error'):
                            self._handle_error(Exception(f'30秒内出现{error_count}个错误'), 'high_error_rate')
                        last_error_time = current_time
                        error_count = 0
                    
                    # 队列溢出保护 - 智能版本
                    max_queue_size = self.config.get('max_queue_size', 50)
                    warning_threshold = int(max_queue_size * 0.8)  # 80%容量时发出警告
                    
                    queue_size = self.frame_queue.qsize()
                    if queue_size > warning_threshold:
                        resource_warning_count += 1
                    
                    if queue_size > max_queue_size:
                        logger.warning(f"队列溢出保护触发: {self.camera_id}, 当前大小: {queue_size}, 最大容量: {max_queue_size}")
                        # 根据队列大小决定清理策略
                        keep_percentage = max(0.1, 1.0 - (queue_size / max_queue_size) * 0.5)
                        keep_count = max(1, int(queue_size * keep_percentage))
                        self._clear_queue_except_latest(self.frame_queue, keep_count)
                    elif resource_warning_count % 5 == 0:  # 每5次警告记录一次日志
                        logger.warning(f"队列接近容量上限: {self.camera_id}, 当前大小: {queue_size}/{max_queue_size}")
                        
                        # 定期资源清理
                        if hasattr(self, 'stats') and current_time % 60 < 1:  # 每分钟执行一次
                            self._cleanup_resources()
                except Exception as nested_e:
                    # 处理嵌套try块中的异常
                    logger.error(f"处理帧时发生异常: {str(nested_e)}", exc_info=True)
                    error_count += 1
                    consecutive_errors += 1
                finally:
                    # 确保frame_queue.task_done()总是被调用
                    if 'frame_data' in locals():
                        self.frame_queue.task_done()
                    
        except Exception as e:
            logger.error(f"处理线程主循环异常: {str(e)}", exc_info=True)
            self.last_error = str(e)
            
            # 主循环异常后的恢复尝试
            self._handle_error(e, "process_loop")
            
            # 更长的休眠时间，避免在严重错误时频繁循环
            time.sleep(1.0)
        finally:
            logger.debug(f"处理线程循环结束: {self.camera_id}")
            # 确保资源被正确释放
            self._cleanup_resources()
            # 清理资源
            logger.info(f"处理线程正在结束，执行资源清理: {self.camera_id}")
            self._cleanup_processing_resources()
            logger.info(f"处理线程结束: {self.camera_id}")
            
    def _adjust_performance(self, adjustment):
        """基于当前性能动态调整处理策略"""
        try:
            current_fps = self.stats.get('fps', 0)
            target_fps = self.config.get('target_fps', 15)  # 可配置的目标FPS
            
            # 根据FPS调整缩放因子
            if current_fps < target_fps * 0.7 and adjustment['current_scale'] > adjustment['min_scale']:
                # FPS过低，降低分辨率
                adjustment['current_scale'] = max(adjustment['min_scale'], adjustment['current_scale'] - adjustment['adjustment_step'])
                logger.info(f"性能调整: {self.camera_id}, 降低处理分辨率，缩放因子: {adjustment['current_scale']:.1f}")
            elif current_fps > target_fps * 1.2 and adjustment['current_scale'] < adjustment['max_scale']:
                # FPS充足，可以提高分辨率
                adjustment['current_scale'] = min(adjustment['max_scale'], adjustment['current_scale'] + adjustment['adjustment_step'])
                logger.info(f"性能调整: {self.camera_id}, 提高处理分辨率，缩放因子: {adjustment['current_scale']:.1f}")
        except Exception as e:
            logger.warning(f"性能调整失败: {str(e)}")
    
    def _should_trigger_alert(self, behavior):
        """判断是否应该触发告警，用于频率限制"""
        # 简单实现，实际应用中可以更复杂
        return True
    
    def _record_alert_trigger(self, behavior):
        """记录告警触发时间，用于频率限制"""
        pass
    
    def _smart_clean_processed_queue(self):
        """智能清理已处理帧队列，优先保留重要帧"""
        try:
            # 简单实现：保留最近的帧
            # 实际应用中可以根据帧内容的重要性（如是否包含检测目标）进行智能清理
            if self.processed_frame_queue.qsize() > 3:
                self._clear_queue_except_latest(self.processed_frame_queue, keep_count=3)
        except Exception as e:
            logger.warning(f"智能清理队列失败: {str(e)}")
    
    # _attempt_recovery方法已在文件上方定义，这里不再重复
            
    # _recover_capture方法已在文件上方定义，这里不再重复
            
            logger.error(f"[{self.camera_id}] 多次尝试后视频捕获初始化失败")
            return False
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 恢复视频捕获失败: {str(e)}")
            return False
            
    def _recover_processing(self):
        """恢复视频处理功能
        
        Returns:
            bool: 恢复是否成功
        """
        try:
            logger.info(f"[{self.camera_id}] 开始恢复视频处理")
            
            # 清理处理相关资源
            self._cleanup_processing_resources()
            
            # 重置处理统计
            if hasattr(self, '_statistics'):
                self._statistics['process_errors'] = 0
            
            logger.info(f"[{self.camera_id}] 视频处理恢复完成")
            return True
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 恢复视频处理失败: {str(e)}")
            # 调用错误处理方法通知系统
            if hasattr(self, '_handle_error'):
                self._handle_error(e, 'processing_recovery_failure')
            return False
            
    def _recover_basic(self):
        """基本恢复策略
        
        Returns:
            bool: 恢复是否成功
        """
        try:
            logger.info(f"[{self.camera_id}] 执行基本恢复策略")
            
            # 重置错误计数器
            if hasattr(self, '_statistics'):
                self._statistics['capture_errors'] = 0
                self._statistics['process_errors'] = 0
            
            # 重置状态标志
            if hasattr(self, '_status'):
                self._status['has_error'] = False
            
            logger.info(f"[{self.camera_id}] 基本恢复完成")
            return True
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 基本恢复失败: {str(e)}")
            # 调用错误处理方法通知系统
            if hasattr(self, '_handle_error'):
                self._handle_error(e, 'basic_recovery_failure')
            return False
    
    # _cleanup_resources方法已在文件上方定义，这里不再重复
    
    def _cleanup_processing_resources(self):
        """处理线程结束时清理资源"""
        try:
            # 清理队列
            self._clear_queue_except_latest(self.frame_queue, keep_count=0)
            self._clear_queue_except_latest(self.processed_frame_queue, keep_count=0)
            
            # 重置内部状态
            if hasattr(self, 'tracks'):
                self.tracks = []
            
            logger.info(f"[{self.camera_id}] 处理线程资源清理完成")
        except Exception as e:
            logger.error(f"[{self.camera_id}] 处理线程资源清理失败: {str(e)}")
            
    def _monitor_system_resources(self):
        """监控系统资源使用情况
        
        Returns:
            dict: 资源使用状态信息
        """
        try:
            # 基础资源使用信息
            resource_info = {
                'timestamp': datetime.now().isoformat(),
                'camera_id': self.camera_id,
                'thread_status': {
                    'capture_alive': False,
                    'process_alive': False
                },
                'queue_status': {
                    'frame_queue_size': 0,
                    'processed_queue_size': 0
                },
                'memory_usage': {
                    'captured_frames': 0,
                    'processed_frames': 0
                }
            }
            
            # 检查线程状态
            if hasattr(self, '_capture_thread'):
                resource_info['thread_status']['capture_alive'] = self._capture_thread.is_alive()
            if hasattr(self, '_process_thread'):
                resource_info['thread_status']['process_alive'] = self._process_thread.is_alive()
            
            # 检查队列状态
            if hasattr(self, 'frame_queue'):
                resource_info['queue_status']['frame_queue_size'] = self.frame_queue.qsize()
            if hasattr(self, 'processed_frame_queue'):
                resource_info['queue_status']['processed_queue_size'] = self.processed_frame_queue.qsize()
            
            # 检查内存使用相关指标
            if hasattr(self, '_statistics'):
                resource_info['memory_usage']['captured_frames'] = self._statistics.get('total_frames', 0)
                resource_info['memory_usage']['processed_frames'] = self._statistics.get('processed_frames', 0)
            
            # 分析资源使用情况
            is_healthy = True
            warnings = []
            
            # 检查线程健康状态
            if resource_info['thread_status']['capture_alive'] and resource_info['thread_status']['process_alive']:
                # 正常状态
                pass
            else:
                is_healthy = False
                warnings.append("线程未正常运行")
            
            # 检查队列积压情况
            frame_queue_size = resource_info['queue_status']['frame_queue_size']
            if frame_queue_size > 100:  # 队列积压阈值
                is_healthy = False
                warnings.append(f"帧队列积压严重: {frame_queue_size}帧")
            elif frame_queue_size > 50:
                warnings.append(f"帧队列轻微积压: {frame_queue_size}帧")
            
            # 检查错误率
            if hasattr(self, '_statistics'):
                total_frames = max(1, self._statistics.get('total_frames', 1))
                total_errors = self._statistics.get('total_errors', 0)
                error_rate = total_errors / total_frames
                
                if error_rate > 0.1:  # 错误率阈值10%
                    is_healthy = False
                    warnings.append(f"错误率过高: {error_rate:.2%}")
                elif error_rate > 0.05:
                    warnings.append(f"错误率较高: {error_rate:.2%}")
            
            # 添加健康状态和警告
            resource_info['health_status'] = {
                'is_healthy': is_healthy,
                'warnings': warnings
            }
            
            # 记录详细监控信息（DEBUG级别）
            logger.debug(f"[{self.camera_id}] 系统资源监控: {resource_info}")
            
            # 如果不健康，记录警告日志
            if not is_healthy:
                logger.warning(f"[{self.camera_id}] 系统资源监控发现问题: {warnings}")
                
                # 触发自动恢复
                if hasattr(self, '_should_auto_recover') and self._should_auto_recover:
                    logger.info(f"[{self.camera_id}] 触发自动恢复")
                    self._attempt_recovery()
            
            return resource_info
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 系统资源监控失败: {str(e)}")
            return None
            
    def _self_diagnosis(self):
        """执行自诊断检查
        
        Returns:
            dict: 诊断结果
        """
        try:
            diagnosis_result = {
                'timestamp': datetime.now().isoformat(),
                'camera_id': self.camera_id,
                'diagnostic_checks': {},
                'is_functional': True,
                'issues': []
            }
            
            # 检查视频捕获状态
            capture_status = self._check_capture_status()
            diagnosis_result['diagnostic_checks']['capture'] = capture_status
            if not capture_status['is_operational']:
                diagnosis_result['is_functional'] = False
                diagnosis_result['issues'].extend(capture_status['issues'])
            
            # 检查处理状态
            processing_status = self._check_processing_status()
            diagnosis_result['diagnostic_checks']['processing'] = processing_status
            if not processing_status['is_operational']:
                diagnosis_result['is_functional'] = False
                diagnosis_result['issues'].extend(processing_status['issues'])
            
            # 检查组件状态
            components_status = self._check_components_status()
            diagnosis_result['diagnostic_checks']['components'] = components_status
            if not components_status['all_operational']:
                diagnosis_result['is_functional'] = False
                diagnosis_result['issues'].extend(components_status['issues'])
            
            # 生成诊断摘要
            if diagnosis_result['is_functional']:
                logger.info(f"[{self.camera_id}] 自诊断通过，所有系统正常运行")
            else:
                logger.warning(f"[{self.camera_id}] 自诊断发现 {len(diagnosis_result['issues'])} 个问题: {diagnosis_result['issues']}")
            
            return diagnosis_result
            
        except Exception as e:
            logger.error(f"[{self.camera_id}] 自诊断过程失败: {str(e)}")
            return {
                'timestamp': datetime.now().isoformat(),
                'camera_id': self.camera_id,
                'diagnostic_checks': {},
                'is_functional': False,
                'issues': [f"自诊断过程失败: {str(e)}"]
            }
            
    def _check_capture_status(self):
        """检查视频捕获状态
        
        Returns:
            dict: 捕获状态信息
        """
        status = {
            'is_operational': True,
            'issues': [],
            'details': {}
        }
        
        try:
            # 检查视频捕获对象
            if not hasattr(self, '_cap') or self._cap is None:
                status['is_operational'] = False
                status['issues'].append("视频捕获对象不存在")
            else:
                # 检查是否打开
                is_opened = self._cap.isOpened()
                status['details']['is_opened'] = is_opened
                
                if not is_opened:
                    status['is_operational'] = False
                    status['issues'].append("视频捕获设备未打开")
                else:
                    # 尝试读取一帧以验证捕获功能
                    try:
                        ret, _ = self._cap.read()
                        status['details']['can_read_frame'] = ret
                        
                        if not ret:
                            status['is_operational'] = False
                            status['issues'].append("无法读取视频帧")
                    except Exception as e:
                        status['is_operational'] = False
                        status['issues'].append(f"读取帧时出错: {str(e)}")
            
            # 检查捕获线程
            if hasattr(self, '_capture_thread'):
                is_alive = self._capture_thread.is_alive()
                status['details']['thread_alive'] = is_alive
                
                if not is_alive:
                    status['issues'].append("捕获线程未运行")
            
        except Exception as e:
            status['is_operational'] = False
            status['issues'].append(f"检查捕获状态失败: {str(e)}")
        
        return status
        
    def _check_processing_status(self):
        """检查视频处理状态
        
        Returns:
            dict: 处理状态信息
        """
        status = {
            'is_operational': True,
            'issues': [],
            'details': {}
        }
        
        try:
            # 检查处理线程
            if hasattr(self, '_process_thread'):
                is_alive = self._process_thread.is_alive()
                status['details']['thread_alive'] = is_alive
                
                if not is_alive:
                    status['issues'].append("处理线程未运行")
            
            # 检查队列状态
            if hasattr(self, 'frame_queue'):
                queue_size = self.frame_queue.qsize()
                status['details']['frame_queue_size'] = queue_size
                
                # 检查队列是否长时间积压
                if hasattr(self, '_statistics'):
                    last_process_time = self._statistics.get('last_process_time')
                    if last_process_time:
                        time_since_last_process = (datetime.now() - last_process_time).total_seconds()
                        status['details']['time_since_last_process'] = time_since_last_process
                        
                        if time_since_last_process > 10:  # 10秒内没有处理新帧
                            status['is_operational'] = False
                            status['issues'].append(f"长时间未处理新帧: {time_since_last_process:.1f}秒")
            
        except Exception as e:
            status['is_operational'] = False
            status['issues'].append(f"检查处理状态失败: {str(e)}")
        
        return status
        
    def _check_components_status(self):
        """检查各个组件状态
        
        Returns:
            dict: 组件状态信息
        """
        status = {
            'all_operational': True,
            'issues': [],
            'components': {}
        }
        
        try:
            # 检查检测器状态
            if hasattr(self, 'detection_engine'):
                try:
                    # 尝试访问检测器的基本属性或方法
                    detector_status = hasattr(self.detection_engine, 'detect')
                    status['components']['detection_engine'] = detector_status
                    
                    if not detector_status:
                        status['all_operational'] = False
                        status['issues'].append("检测器组件不正常")
                except Exception as e:
                    status['components']['detection_engine'] = False
                    status['all_operational'] = False
                    status['issues'].append(f"检测器组件检查失败: {str(e)}")
            
            # 检查其他可能的组件...
            
        except Exception as e:
            status['all_operational'] = False
            status['issues'].append(f"组件状态检查失败: {str(e)}")
        
        return status
    
    def _clear_queue_except_latest(self, queue_to_clear, keep_count=1):
        """清理队列中除了最新几帧以外的所有帧
        
        Args:
            queue_to_clear: 需要清理的队列
            keep_count: 保留的帧数
        """
        try:
            if queue_to_clear.qsize() <= keep_count:
                return
                
            # 保存最新的几帧
            latest_items = []
            count_cleared = 0
            
            while not queue_to_clear.empty():
                try:
                    item = queue_to_clear.get_nowait()
                    if len(latest_items) < keep_count:
                        latest_items.append(item)
                    else:
                        count_cleared += 1
                        # 释放帧资源
                        if isinstance(item, dict) and 'frame' in item:
                            del item['frame']
                        # 确保标记任务完成
                        try:
                            queue_to_clear.task_done()
                        except:
                            pass
                except queue.Empty:
                    break
            
            # 将最新的帧放回队列
            for item in reversed(latest_items):  # 保持原始顺序
                queue_to_clear.put(item)
            
            logger.debug(f"队列清理完成，保留最新{keep_count}帧，清理了 {count_cleared} 帧: {self.camera_id}")
        except Exception as e:
            logger.error(f"清理队列失败: {str(e)}")
        
    # 注意：上面已经定义了增强版的_clear_queue_except_latest方法，这里不再需要旧版本
        """清理队列中除了最新帧以外的所有帧
        
        Args:
            queue_to_clear: 需要清理的队列
        """
        try:
            if queue_to_clear.qsize() <= 1:
                return
                
            # 保存最新的一帧
            latest_item = None
            count_cleared = 0
            
            while not queue_to_clear.empty():
                try:
                    item = queue_to_clear.get_nowait()
                    if not latest_item:
                        latest_item = item
                    else:
                        count_cleared += 1
                        # 确保标记任务完成
                        try:
                            queue_to_clear.task_done()
                        except:
                            pass
                except queue.Empty:
                    break
            
            # 将最新的帧放回队列
            if latest_item:
                queue_to_clear.put(latest_item)
            
            logger.debug(f"队列清理完成，保留最新帧，清理了 {count_cleared} 帧: {self.camera_id}")
        except Exception as e:
            logger.error(f"清理队列失败: {str(e)}")
    
    def _visualize_frame(self, frame_data: Dict[str, Any]):
        """可视化帧数据
        
        Args:
            frame_data: 帧数据字典
        """
        try:
            # 输入验证
            if not isinstance(frame_data, dict):
                logger.error(f"可视化帧数据失败: 输入不是字典类型")
                return
                
            if 'frame' not in frame_data:
                logger.error(f"可视化帧数据失败: 缺少帧数据")
                return
                
            frame = frame_data['frame']
            
            # 验证帧是否有效
            if frame is None or frame.size == 0:
                logger.warning(f"帧数据为空，跳过可视化: {self.camera_id}")
                return
                
            # 绘制检测框
            try:
                if 'detections' in frame_data and isinstance(frame_data['detections'], list):
                    for detection in frame_data['detections']:
                        try:
                            if not isinstance(detection, dict):
                                continue
                                
                            # 安全获取边界框信息
                            bbox = detection.get('bbox', [0, 0, 0, 0])
                            if len(bbox) < 4:
                                continue
                                
                            x1, y1, x2, y2 = bbox
                            class_name = detection.get('class_name', 'Unknown')
                            confidence = detection.get('confidence', 0.0)
                            
                            # 边界检查，确保坐标在有效范围内
                            h, w = frame.shape[:2] if len(frame.shape) >= 2 else (0, 0)
                            x1, y1 = max(0, min(int(x1), w)), max(0, min(int(y1), h))
                            x2, y2 = max(0, min(int(x2), w)), max(0, min(int(y2), h))
                            
                            # 确保矩形有效
                            if x2 > x1 and y2 > y1:
                                # 绘制边界框
                                color = (0, 255, 0)  # 默认绿色
                                cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
                                
                                # 绘制标签，确保位置有效
                                label_pos = (x1, max(10, y1 - 10))  # 确保不会出界
                                label = f"{class_name}: {confidence:.2f}"
                                cv2.putText(
                                    frame,
                                    label,
                                    label_pos,
                                    cv2.FONT_HERSHEY_SIMPLEX,
                                    0.5,
                                    color,
                                    2
                                )
                        except Exception as e:
                            logger.debug(f"绘制检测框错误: {str(e)}")
            except Exception as e:
                logger.warning(f"绘制检测信息失败: {str(e)}")
        
            # 绘制跟踪
            try:
                if 'tracks' in frame_data and isinstance(frame_data['tracks'], list):
                    for track in frame_data['tracks']:
                        try:
                            if not isinstance(track, dict):
                                continue
                                
                            # 安全获取跟踪信息
                            track_id = track.get('track_id', 'N/A')
                            bbox = track.get('bbox', [0, 0, 0, 0])
                            if len(bbox) < 4:
                                continue
                                
                            x1, y1, x2, y2 = bbox
                            class_name = track.get('class_name', 'Unknown')
                            
                            # 边界检查
                            h, w = frame.shape[:2] if len(frame.shape) >= 2 else (0, 0)
                            x1, y1 = max(0, min(int(x1), w)), max(0, min(int(y1), h))
                            x2, y2 = max(0, min(int(x2), w)), max(0, min(int(y2), h))
                            
                            if x2 > x1 and y2 > y1:
                                # 为每个跟踪ID生成唯一颜色
                                try:
                                    color = self._get_color_for_id(track_id)
                                except Exception as e:
                                    logger.debug(f"生成颜色错误: {str(e)}")
                                    color = (0, 165, 255)  # 默认橙色
                                
                                # 绘制边界框
                                cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2)
                                
                                # 绘制跟踪ID和类别
                                label_pos = (x1, max(10, y1 - 10))
                                label = f"ID: {track_id}, {class_name}"
                                cv2.putText(
                                    frame,
                                    label,
                                    label_pos,
                                    cv2.FONT_HERSHEY_SIMPLEX,
                                    0.5,
                                    color,
                                    2
                                )
                        except Exception as e:
                            logger.debug(f"绘制跟踪框错误: {str(e)}")
            except Exception as e:
                logger.warning(f"绘制跟踪信息失败: {str(e)}")
        
            # 绘制行为分析结果
            try:
                if 'behaviors' in frame_data and isinstance(frame_data['behaviors'], list):
                    for behavior in frame_data['behaviors']:
                        try:
                            if not isinstance(behavior, dict) or not behavior.get('is_violation', False):
                                continue
                                
                            # 找到相关的跟踪对象
                            track_id = behavior.get('track_id')
                            if track_id and 'tracks' in frame_data and isinstance(frame_data['tracks'], list):
                                for track in frame_data['tracks']:
                                    try:
                                        if track.get('track_id') == track_id and isinstance(track, dict):
                                            bbox = track.get('bbox', [0, 0, 0, 0])
                                            if len(bbox) < 4:
                                                continue
                                                
                                            x1, y1, x2, y2 = bbox
                                            violation_type = behavior.get('type', 'Unknown')
                                            
                                            # 边界检查
                                            h, w = frame.shape[:2] if len(frame.shape) >= 2 else (0, 0)
                                            x1, y1 = max(0, min(int(x1), w)), max(0, min(int(y1), h))
                                            x2, y2 = max(0, min(int(x2), w)), max(0, min(int(y2), h))
                                            
                                            if x2 > x1 and y2 > y1:
                                                # 绘制红色边界框表示违规
                                                cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 3)
                                                
                                                # 绘制违规标签，确保位置有效
                                                violation_label_pos = (x1, max(30, y1 - 30))
                                                violation_label = f"VIOLATION: {violation_type}"
                                                cv2.putText(
                                                    frame,
                                                    violation_label,
                                                    violation_label_pos,
                                                    cv2.FONT_HERSHEY_SIMPLEX,
                                                    0.5,
                                                    (0, 0, 255),
                                                    2
                                                )
                                            break
                                    except Exception as e:
                                        logger.debug(f"处理违规跟踪错误: {str(e)}")
                        except Exception as e:
                            logger.debug(f"绘制行为分析结果错误: {str(e)}")
            except Exception as e:
                logger.warning(f"绘制行为分析信息失败: {str(e)}")
        
            # 绘制摄像头信息和状态
            try:
                # 基本信息绘制，使用异常处理确保即使某些信息错误也能继续
                try:
                    camera_info = f"Camera: {self.camera_id}"
                    cv2.putText(frame, camera_info, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
                except Exception as e:
                    logger.debug(f"绘制摄像头信息错误: {str(e)}")
                
                try:
                    status_info = f"Status: {self.status}"
                    cv2.putText(frame, status_info, (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
                except Exception as e:
                    logger.debug(f"绘制状态信息错误: {str(e)}")
                
                try:
                    fps_info = f"FPS: {self.stats.get('fps', 0.0):.1f}"
                    cv2.putText(frame, fps_info, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
                except Exception as e:
                    logger.debug(f"绘制FPS信息错误: {str(e)}")
                
                # 绘制场景信息
                try:
                    # 尝试从frame_data中获取场景信息
                    scene_info = None
                    if 'current_scene' in frame_data and isinstance(frame_data['current_scene'], dict):
                        scene_info = frame_data['current_scene']
                    elif 'scene' in frame_data and isinstance(frame_data['scene'], dict):
                        scene_info = frame_data['scene']
                    
                    if scene_info:
                        scene_type = scene_info.get('type', 'Unknown')
                        scene_confidence = scene_info.get('confidence', 0.0)
                        scene_text = f"Scene: {scene_type} ({scene_confidence:.2f})"
                        cv2.putText(frame, scene_text, (10, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2)
                except Exception as e:
                    logger.debug(f"绘制场景信息错误: {str(e)}")
                
                # 如果有错误信息，在屏幕上显示
                if self.last_error:
                    error_info = f"Error: {self.last_error[:30]}..." if len(self.last_error) > 30 else f"Error: {self.last_error}"
                    cv2.putText(frame, error_info, (10, frame.shape[0] - 10), 
                               cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
            except Exception as e:
                logger.warning(f"绘制信息文本失败: {str(e)}")
        
            # 更新帧数据中的帧
            frame_data['frame'] = frame
            logger.debug(f"帧可视化完成: {self.camera_id}")
            
        except Exception as e:
            logger.error(f"帧可视化过程中发生错误: {str(e)}")
            # 确保frame_data中的帧仍然有效，即使可视化失败
    
    def _get_color_for_id(self, track_id: str) -> tuple:
        """为跟踪ID生成唯一颜色
        
        Args:
            track_id: 跟踪ID
            
        Returns:
            颜色RGB元组
        """
        # 使用简单的哈希函数生成颜色
        import hashlib
        hash_val = int(hashlib.md5(str(track_id).encode()).hexdigest(), 16) % (256**3)
        r = int((hash_val >> 16) & 0xFF)
        g = int((hash_val >> 8) & 0xFF)
        b = int(hash_val & 0xFF)
        return (b, g, r)  # OpenCV使用BGR格式
    
    def get_current_frame(self) -> Optional[Dict[str, Any]]:
        """获取当前帧
        
        Returns:
            当前帧数据字典
        """
        try:
            # 尝试从已处理帧队列获取最新帧
            if not self.processed_frame_queue.empty():
                # 注意：这里只返回队列中的最新帧，但不移除它
                # 实际应用中可能需要更复杂的逻辑来获取最新帧
                frames = []
                while not self.processed_frame_queue.empty():
                    frame = self.processed_frame_queue.get()
                    frames.append(frame)
                
                # 将所有帧放回队列
                for frame in frames[:-1]:  # 除了最后一帧
                    try:
                        self.processed_frame_queue.put(frame, block=False)
                    except queue.Full:
                        break
                
                # 返回最后一帧
                if frames:
                    return frames[-1]
            
            return None
            
        except Exception as e:
            logger.error(f"获取当前帧错误: {str(e)}")
            return None
    
    def get_snapshot(self) -> Optional[np.ndarray]:
        """获取当前快照
        
        Returns:
            图像数组
        """
        frame_data = self.get_current_frame()
        if frame_data and 'frame' in frame_data:
            return frame_data['frame'].copy()
        return None
    
    def set_callbacks(self, **callbacks):
        """设置回调函数
        
        Args:
            callbacks: 回调函数字典
        """
        with self.lock:
            if 'on_frame' in callbacks:
                self.on_frame_callback = callbacks['on_frame']
            if 'on_processed_frame' in callbacks:
                self.on_processed_frame_callback = callbacks['on_processed_frame']
            if 'on_detection' in callbacks:
                self.on_detection_callback = callbacks['on_detection']
            if 'on_alert' in callbacks:
                self.on_alert_callback = callbacks['on_alert']
    
    def get_status(self) -> Dict[str, Any]:
        """获取处理器状态
        
        Returns:
            状态信息字典
        """
        with self.lock:
            return {
                'camera_id': self.camera_id,
                'source': self.source,
                'status': self.status,
                'resolution': (self.frame_width, self.frame_height),
                'fps': self.fps,
                'stats': copy.deepcopy(self.stats),
                'last_error': self.last_error,
                'is_running': self.running,
                'frame_count': self.frame_count
            }
    
    def update_config(self, config: Dict[str, Any]) -> bool:
        """更新配置
        
        Args:
            config: 新的配置字典
        
        Returns:
            bool: 是否更新成功
        """
        try:
            # 输入验证
            if not isinstance(config, dict):
                logger.error(f"配置必须是字典类型: {self.camera_id}, 收到类型: {type(config).__name__}")
                self.last_error = "配置必须是字典类型"
                return False
            
            if not config:
                logger.warning(f"空配置，无需更新: {self.camera_id}")
                return True
            
            with self.lock:
                logger.info(f"开始更新视频处理器配置: {self.camera_id}")
                
                # 保存旧配置，以便在更新失败时回滚
                old_config = self.config.copy()
                updated_keys = []
                validation_errors = []
                
                # 验证配置有效性
                for key, value in config.items():
                    # 对特定配置项进行验证
                    if key == 'max_frame_age':
                        if not isinstance(value, (int, float)) or value <= 0:
                            validation_errors.append(f"max_frame_age必须是正数，当前值: {value}")
                            continue
                    elif key == 'frame_interval':
                        if not isinstance(value, (int, float)) or value <= 0:
                            validation_errors.append(f"frame_interval必须是正数，当前值: {value}")
                            continue
                    elif key == 'resolution':
                        if not isinstance(value, (tuple, list)) or len(value) != 2 or \
                           not all(isinstance(v, int) and v > 0 for v in value):
                            validation_errors.append(f"resolution必须是包含两个正整数的元组/列表，当前值: {value}")
                            continue
                    
                    updated_keys.append(key)
                
                # 如果有验证错误，返回失败
                if validation_errors:
                    for error in validation_errors:
                        logger.error(f"{self.camera_id}: {error}")
                    
                    self.last_error = f"配置验证失败: {'; '.join(validation_errors)}"
                    logger.warning(f"配置更新验证失败: {self.camera_id}")
                    return False
                
                # 记录更新前的关键配置值用于日志对比
                old_values = {}
                if 'max_frame_age' in config:
                    old_values['max_frame_age'] = getattr(self, 'max_frame_age', '未设置')
                if 'frame_interval' in config:
                    old_values['frame_interval'] = getattr(self, 'frame_interval', '未设置')
                if 'resolution' in config:
                    old_values['resolution'] = getattr(self, 'resolution', '未设置')
                
                try:
                    # 更新配置
                    self.config.update(config)
                    
                    # 更新相关配置到实例变量
                    if 'max_frame_age' in config:
                        self.max_frame_age = config['max_frame_age']
                        logger.info(f"{self.camera_id}: max_frame_age已更新: {old_values['max_frame_age']} -> {self.max_frame_age}")
                    
                    if 'frame_interval' in config:
                        self.frame_interval = config['frame_interval']
                        logger.info(f"{self.camera_id}: frame_interval已更新: {old_values['frame_interval']} -> {self.frame_interval}")
                        # 计算FPS用于日志展示
                        fps = 1.0 / self.frame_interval if self.frame_interval > 0 else 0
                        logger.debug(f"{self.camera_id}: 目标FPS: {fps:.2f}")
                    
                    if 'resolution' in config:
                        self.resolution = config['resolution']
                        logger.info(f"{self.camera_id}: resolution已更新: {old_values['resolution']} -> {self.resolution}")
                        
                        # 如果正在运行且分辨率已更改，提醒用户可能需要重启
                        if hasattr(self, 'running') and self.running and hasattr(self, 'cap') and self.cap is not None:
                            logger.warning(f"{self.camera_id}: 分辨率已更改，某些更改可能需要重启才能完全生效")
                    
                    # 记录成功更新的配置
                    logger.info(f"视频处理器配置更新成功: {self.camera_id}, 更新的配置键: {', '.join(updated_keys)}")
                    
                    # 更新统计信息
                    if hasattr(self, 'stats'):
                        self.stats['last_config_update'] = time.time()
                        self.stats['config_updates'] = self.stats.get('config_updates', 0) + 1
                    
                    return True
                    
                except Exception as e:
                    # 更新过程中出现异常，回滚配置
                    logger.error(f"{self.camera_id}: 配置更新过程中出错: {str(e)}", exc_info=True)
                    self.config = old_config
                    self.last_error = f"配置更新失败: {str(e)}"
                    return False
                    
        except Exception as e:
            logger.error(f"{self.camera_id}: 配置更新时发生意外错误: {str(e)}", exc_info=True)
            self.last_error = f"配置更新意外失败: {str(e)}"
            return False
    
    def is_alive(self) -> bool:
        """检查处理器是否正常运行
        
        Returns:
            bool: 是否正常运行
        """
        try:
            with self.lock:
                # 初始化诊断信息
                diagnostic_info = {
                    'camera_id': self.camera_id,
                    'running_state': False,
                    'reason': '',
                    'capture_thread_alive': False,
                    'process_thread_alive': False,
                    'status': 'unknown',
                    'last_frame_time': 'unknown',
                    'frame_age': -1
                }
                
                # 检查基本运行状态
                if not hasattr(self, 'running') or not self.running:
                    diagnostic_info['reason'] = '处理器未运行'
                    logger.debug(f"视频处理器状态检查: {self.camera_id}, 结果: 未运行")
                    return False
                diagnostic_info['running_state'] = True
                
                # 检查状态是否为错误
                if hasattr(self, 'status') and self.status == 'error':
                    diagnostic_info['reason'] = '处理器处于错误状态'
                    diagnostic_info['status'] = self.status
                    logger.warning(f"视频处理器状态检查: {self.camera_id}, 结果: 错误状态 ({self.status})")
                    return False
                if hasattr(self, 'status'):
                    diagnostic_info['status'] = self.status
                
                # 检查是否有最近的错误
                if hasattr(self, 'last_error') and self.last_error:
                    diagnostic_info['reason'] = '存在未解决的错误'
                    logger.warning(f"视频处理器状态检查: {self.camera_id}, 结果: 存在错误 - {self.last_error}")
                    # 注意：我们不直接返回False，而是记录警告，因为短暂错误后可能已恢复
                
                # 检查捕获线程状态
                capture_alive = False
                if hasattr(self, 'capture_thread') and self.capture_thread:
                    try:
                        capture_alive = self.capture_thread.is_alive()
                        diagnostic_info['capture_thread_alive'] = capture_alive
                    except Exception as e:
                        logger.error(f"检查捕获线程状态时出错: {str(e)}")
                
                # 检查处理线程状态
                process_alive = False
                if hasattr(self, 'process_thread') and self.process_thread:
                    try:
                        process_alive = self.process_thread.is_alive()
                        diagnostic_info['process_thread_alive'] = process_alive
                    except Exception as e:
                        logger.error(f"检查处理线程状态时出错: {str(e)}")
                
                # 如果任一线程未运行，返回False
                if not capture_alive or not process_alive:
                    diagnostic_info['reason'] = '处理线程未运行'
                    thread_status = f"捕获线程: {'运行' if capture_alive else '停止'}, 处理线程: {'运行' if process_alive else '停止'}"
                    logger.warning(f"视频处理器状态检查: {self.camera_id}, 结果: 线程异常 - {thread_status}")
                    return False
                
                # 检查视频捕获是否有效
                if hasattr(self, 'cap') and hasattr(self.cap, 'isOpened'):
                    try:
                        if not self.cap.isOpened():
                            diagnostic_info['reason'] = '视频捕获未打开'
                            logger.warning(f"视频处理器状态检查: {self.camera_id}, 结果: 视频捕获未打开")
                            return False
                    except Exception as e:
                        logger.error(f"检查视频捕获状态时出错: {str(e)}")
                
                # 检查是否有最近处理的帧
                current_time = time.time()
                frame_age_threshold = 10  # 10秒没有新帧认为异常
                if hasattr(self, 'stats') and isinstance(self.stats, dict) and 'last_frame_time' in self.stats:
                    last_frame_time = self.stats['last_frame_time']
                    diagnostic_info['last_frame_time'] = last_frame_time
                    
                    if last_frame_time > 0:
                        frame_age = current_time - last_frame_time
                        diagnostic_info['frame_age'] = frame_age
                        
                        if frame_age > frame_age_threshold:
                            diagnostic_info['reason'] = '长时间无新帧'
                            logger.warning(
                                f"视频处理器状态检查: {self.camera_id}, "
                                f"结果: 帧超时 - 最后帧时间: {last_frame_time:.2f}s, "
                                f"当前时间: {current_time:.2f}s, "
                                f"间隔: {frame_age:.2f}s"
                            )
                            return False
                
                # 检查队列健康状态
                if hasattr(self, 'frame_queue'):
                    try:
                        queue_size = self.frame_queue.qsize()
                        max_queue_size = getattr(self, 'max_queue_size', 30)
                        if queue_size > max_queue_size * 0.8:  # 如果队列超过80%容量
                            logger.warning(
                                f"视频处理器状态检查: {self.camera_id}, "
                                f"警告: 帧队列积压 - 当前大小: {queue_size}, "
                                f"最大大小: {max_queue_size}"
                            )
                    except Exception as e:
                        logger.error(f"检查队列状态时出错: {str(e)}")
                
                # 所有检查通过，记录正常状态
                logger.debug(
                    f"视频处理器状态检查: {self.camera_id}, "
                    f"结果: 正常运行 - "
                    f"状态: {diagnostic_info['status']}, "
                    f"线程: 正常, "
                    f"最后帧时间: {diagnostic_info['last_frame_time']}"
                )
                
                return True
                
        except Exception as e:
            # 异常处理
            logger.error(
                f"视频处理器状态检查时发生异常: {self.camera_id}, "
                f"错误: {str(e)}", 
                exc_info=True
            )
            # 当检查本身出错时，我们不能确定处理器状态，但返回False更安全
            return False
    
    def restart(self) -> bool:
        """重启视频处理器
        
        Returns:
            bool: 是否成功重启
        """
        restart_start_time = time.time()
        restart_success = False
        logger.info(f"开始重启视频处理器: {self.camera_id}")
        
        try:
            # 记录重启前的状态用于对比
            prev_status = getattr(self, 'status', 'unknown')
            prev_frame_count = getattr(self, 'frame_count', 0)
            logger.info(f"重启前状态: {self.camera_id}, 状态: {prev_status}, 已处理帧数: {prev_frame_count}")
            
            # 首先停止处理器
            logger.debug(f"正在停止视频处理器: {self.camera_id}")
            stop_success = False
            stop_attempts = 3  # 最大停止尝试次数
            
            for attempt in range(stop_attempts):
                try:
                    # 调用stop方法
                    if hasattr(self, 'stop') and callable(self.stop):
                        stop_success = self.stop()
                        
                        if stop_success:
                            logger.info(f"视频处理器停止成功: {self.camera_id}, 尝试次数: {attempt + 1}")
                            break
                        else:
                            logger.warning(f"视频处理器停止失败: {self.camera_id}, 尝试次数: {attempt + 1}/{stop_attempts}")
                            # 等待一段时间后重试
                            if attempt < stop_attempts - 1:
                                import time
                                time.sleep(0.5)
                    else:
                        logger.error(f"视频处理器没有stop方法: {self.camera_id}")
                        break
                except Exception as e:
                    logger.error(f"停止视频处理器时发生异常: {self.camera_id}, 错误: {str(e)}", exc_info=True)
                    if attempt < stop_attempts - 1:
                        import time
                        time.sleep(0.5)
            
            if not stop_success:
                logger.error(f"视频处理器停止失败，无法重启: {self.camera_id}")
                self.last_error = "无法停止处理器进行重启"
                return False
            
            # 确保完全停止，添加一个小延迟
            import time
            time.sleep(1.0)
            
            # 重置关键状态
            try:
                # 重置帧计数和统计信息
                if hasattr(self, 'frame_count'):
                    self.frame_count = 0
                
                if hasattr(self, 'stats') and isinstance(self.stats, dict):
                    self.stats['restart_count'] = self.stats.get('restart_count', 0) + 1
                    self.stats['last_restart_time'] = time.time()
                    self.stats['start_time'] = time.time()
                    self.stats['processed_frames'] = 0
                    self.stats['fps'] = 0
                    self.stats['last_frame_time'] = 0
                    self.stats['errors'] = 0
                
                # 清除最后错误信息
                if hasattr(self, 'last_error'):
                    self.last_error = None
                
                logger.debug(f"视频处理器状态已重置: {self.camera_id}")
            except Exception as e:
                logger.error(f"重置处理器状态时出错: {self.camera_id}, 错误: {str(e)}", exc_info=True)
            
            # 重新启动处理器
            logger.debug(f"正在启动视频处理器: {self.camera_id}")
            start_success = False
            start_attempts = 3  # 最大启动尝试次数
            
            for attempt in range(start_attempts):
                try:
                    # 调用start或run方法（取决于实现）
                    if hasattr(self, 'start') and callable(self.start):
                        start_success = self.start()
                    elif hasattr(self, 'run') and callable(self.run):
                        start_success = self.run()
                    else:
                        logger.error(f"视频处理器没有start或run方法: {self.camera_id}")
                        break
                    
                    if start_success:
                        logger.info(f"视频处理器启动成功: {self.camera_id}, 尝试次数: {attempt + 1}")
                        break
                    else:
                        logger.warning(f"视频处理器启动失败: {self.camera_id}, 尝试次数: {attempt + 1}/{start_attempts}")
                        # 等待一段时间后重试
                        if attempt < start_attempts - 1:
                            time.sleep(1.0)
                except Exception as e:
                    logger.error(f"启动视频处理器时发生异常: {self.camera_id}, 错误: {str(e)}", exc_info=True)
                    if attempt < start_attempts - 1:
                        time.sleep(1.0)
            
            if not start_success:
                logger.error(f"视频处理器启动失败: {self.camera_id}")
                self.last_error = "重启失败：无法启动处理器"
                return False
            
            # 验证重启是否成功
            logger.debug(f"正在验证重启是否成功: {self.camera_id}")
            verify_success = False
            
            for attempt in range(3):
                time.sleep(0.5)  # 等待启动完成
                
                if hasattr(self, 'is_alive') and callable(self.is_alive):
                    if self.is_alive():
                        verify_success = True
                        break
                    else:
                        logger.debug(f"重启验证中: {self.camera_id}, 尝试次数: {attempt + 1}/3")
                else:
                    # 如果没有is_alive方法，检查running状态
                    if hasattr(self, 'running') and self.running:
                        verify_success = True
                        break
            
            if verify_success:
                restart_success = True
                restart_duration = time.time() - restart_start_time
                
                # 更新统计信息
                if hasattr(self, 'stats') and isinstance(self.stats, dict):
                    self.stats['last_restart_duration'] = restart_duration
                
                logger.info(
                    f"视频处理器重启成功: {self.camera_id}, "
                    f"耗时: {restart_duration:.2f}秒, "
                    f"重启次数: {self.stats.get('restart_count', 1)}次"
                )
            else:
                logger.error(f"视频处理器重启验证失败: {self.camera_id}")
                self.last_error = "重启失败：处理器未正常运行"
            
            return restart_success
            
        except Exception as e:
            logger.error(f"视频处理器重启过程中发生异常: {self.camera_id}, 错误: {str(e)}", exc_info=True)
            self.last_error = f"重启过程异常: {str(e)}"
            return False
        finally:
            # 记录重启结果
            if restart_success:
                logger.info(f"视频处理器重启完成: {self.camera_id}, 结果: 成功")
            else:
                logger.error(f"视频处理器重启完成: {self.camera_id}, 结果: 失败")
    
    def __del__(self):
        """析构函数，确保资源正确释放"""
        try:
            self.stop()
        except:
            pass  # 忽略析构函数中的错误

def _process_loop(self):
        """处理视频帧的主循环"""
        # 初始化变量
        error_count = 0
        frame_count = 0
        try:
            logger.info(f"[{self.camera_id}] 处理线程已启动")
            
            while self.running:
                # 基本的循环结构
                if hasattr(self, 'stopped') and self.stopped:
                    break
                
                try:
                    # 处理队列中的帧
                    max_queue_size = self.config.get('max_queue_size', 50)
                    
                    # 获取帧并进行处理
                    if hasattr(self, 'frame_queue') and not self.frame_queue.empty():
                        # 从队列中获取帧
                        frame_data = self.frame_queue.get(timeout=1.0)
                        
                        if frame_data is None:
                            continue
                        
                        # 提取帧和时间戳
                        if isinstance(frame_data, tuple) and len(frame_data) >= 2:
                            frame = frame_data[0]
                            timestamp = frame_data[1]
                        else:
                            frame = frame_data
                            timestamp = datetime.datetime.now()
                        
                        frame_count += 1
                        
                        # 按照配置的间隔处理帧
                        frame_interval = self.config.get('frame_interval', 1)
                        if frame_count % frame_interval != 0:
                            continue
                        
                        # 目标检测
                        if hasattr(self, 'detection_engine') and self.detection_engine:
                            try:
                                # 执行目标检测
                                detection_results = self.detection_engine.detect(frame)
                                
                                # 处理检测结果
                                if detection_results:
                                    # 触发检测回调
                                    if hasattr(self, 'on_detection_callback') and self.on_detection_callback:
                                        try:
                                            self.on_detection_callback(self.camera_id, detection_results, timestamp)
                                        except Exception as cb_e:
                                            logger.error(f"检测回调执行失败: {str(cb_e)}")
                            except Exception as det_e:
                                logger.error(f"目标检测失败: {str(det_e)}")
                                
                        # 更新统计信息
                        if hasattr(self, 'stats') and isinstance(self.stats, dict):
                            self.stats['frames_processed'] += 1
                    else:
                        # 队列为空时短暂休眠
                        time.sleep(0.01)
                except queue.Empty:
                    # 队列为空异常，继续下一次循环
                    continue
                except Exception as e:
                    # 处理单帧处理过程中的错误
                    logger.error(f"处理单帧时出错: {str(e)}")
                    error_count += 1
                    
                    # 错误计数超过阈值时尝试恢复
                    if error_count >= 10:
                        logger.warning(f"连续错误次数过多，重置错误计数")
                        error_count = 0
                        
                        # 尝试自动恢复
                        if hasattr(self, '_attempt_recovery') and callable(self._attempt_recovery):
                            try:
                                self._attempt_recovery('_process_loop')
                            except Exception as rec_e:
                                logger.error(f"恢复过程出错: {str(rec_e)}")
                    
                    # 短暂休眠避免CPU占用过高
                    time.sleep(0.1)
                
        except Exception as e:
            # 错误处理
            logger.error(f"处理循环出错: {str(e)}")
            # 更新错误统计
            if hasattr(self, 'stats') and isinstance(self.stats, dict):
                self.stats['process_errors'] += 1
                self.stats['total_errors'] += 1
            # 错误率过高时触发警告和恢复
            error_count = 0
        finally:
            # 清理资源
            logger.info(f"[{self.camera_id}] 处理线程已停止")
            # 确保线程状态正确设置
            if hasattr(self, 'process_thread'):
                self.process_thread = None
            # 清空处理队列
            if hasattr(self, 'frame_queue'):
                while not self.frame_queue.empty():
                    try:
                        self.frame_queue.get_nowait()
                    except queue.Empty:
                        break